<?php

/**
 * @Author:      lyt
 * @DateTime:    2016-01-06 09:53:59
 * @Description: 用于订单的操作
 */
class ScsOrderController extends BaseController
{
    /*
     * 订单列表
     * http://api.anhui.com/v1/scs/order/lists?token=b5ce501fdbf0ad0436a89ac8cbaef1f6&user_id=1879&limit=2&offset=2
     * */
    public function lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get("user_id");
            $shop_id = Input::get("shop_id");
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 1);

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $sql="SELECT  * FROM  (
                    SELECT shop_id,order_id,pay_time,start_time, end_time,book_time,book_hour,place,order_type,status,created_at,
                        car_no, phone,car_brand_id, car_brand_name,car_series_id,car_series_name,car_model_id,car_model_name,mileage,is_call,call_status,amount,payable_amount
                    FROM
                        `orders`
                    WHERE   user_id = ".$user_id."
                    AND `status` IN (1018,1112,1213,1214,1215,1216,1217,1219,1317,1411,1412,1416,1417,1419,1420,1117,1312)
                    UNION ALL
                    SELECT shop_id,order_id,pay_time,begin_time AS start_time,end_time,date_format(created_at, '%Y-%m-%d') book_time,
                        '' book_hour,2 place,3 order_type,status,created_at,car_no,phone,'' car_brand_id,'' car_brand_name,
                        '' car_series_id,'' car_series_name,'' car_model_id,'' car_model_name,0 mileage, 0 is_call, 0 call_status,amount,pay_amount as payable_amount
                    FROM
                        car_wash_order
                    WHERE
                        user_id = ".$user_id."
                ) AS temp ";
            $filt="";
            if($shop_id != ''){
                $filt.=$filt==""?"where shop_id=".$shop_id:" and shop_id= ".$shop_id;
            }
            $sql=$sql.$filt;
            $limitsql= ' limit '.$page_size*($page-1).','.$page_size;
            $count=DB::select("select count(1) count from( ".$sql.") as count");
            $sql=$sql." order by created_at desc ";
            $orders=DB::select($sql.$limitsql);
            // $orders = Orders::OrderBy('created_at','desc')
            //     ->where('user_id',$user_id)
            //     ->select(array('order_id','mileage','created_at','pay_time','car_no','car_brand_name','car_series_name','car_model_name','amount','payable_amount','status'))
            //     ->skip($page_size*($page-1))
            //     ->take($page_size);
            // $count = Orders::where('user_id',$user_id);
            // if($shop_id != ''){
            //     $orders->where('shop_id',$shop_id);
            //     $count->where('shop_id',$shop_id);
            // }
            // $orders = $orders->get()->toArray();
            foreach ($orders as &$_order){
                $_order->amount = $_order->amount/100;
                $_order->payable_amount =$_order->payable_amount/100;
            }


            // $count = $count->count();

            $result = array(
                'count' => $count[0]->count,
                'orders' => $orders
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "order", "event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:          zk
     * @DateTime:        18-5-7 下午1:30
     * @Description:     获取本门店sc管理员用户列表
     * @param string $token     用户token
     * @param int $title        用户类型 [1:店长;2:总监;3:前台;]
     * @param string $real_name 真实姓名 [支持模糊查询]
     * @link http://api.anhui.com/v1/scs/order/get_user_list?token=38cf7a76ffc352f7e8249a9c77a80cca
     */
    public function get_user_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user = $this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $shop_id = $sc_user->shop_id;       //本门店id
            $title = Input::get('title', '');
            $real_name = Input::get('real_name', '');
            
            $user_list = SCUser::select('id', 'real_name', 'title')
                    ->where('status', 1)
                    ->where('shop_id', $shop_id);
            if($title != ''){
                $user_list->where('title', $title);
            }
            if($real_name != ''){
                $user_list->where('real_name', 'like', '%'.$real_name.'%');
            }
            $user_list = $user_list->get()->toArray();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $user_list);
        }while(false);
        
        Log::info("info", array("system" => "scs" ,"event" => "get_user_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-01-06 13:43:32
     * @Description: 订单详情
     * @link http://api.anhui.com/v1/scs/order/show?token=38cf7a76ffc352f7e8249a9c77a80cca&order_id=14979549568663
     */
    public function show(){
    	$validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
    	do{
    		if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id = Input::get('order_id');
            $order=Orders::find($order_id);
            if(is_null($order)){//服务单才判断
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            // if($order->place!=2){//如果不是到店
            //     $response = Lang::get("scs_error.order_notexiet_40000");
            //     break;
            // }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;

            }
            $select_arr = [
                'users.id','users.phone','users.register_source_id','users.real_name','users.sex','users.type',
                'user_account.account_no','user_account.balance','user_account.credit','users.u_dis',
                "user_label_activity_type.name as user_label_activity",'users.member', 'users.experience',
                'member_ordinary.name AS member_level_name', 'member_ordinary.dis AS member_dis',
            ];
            $user=Users::where("users.id",$order->user_id)
                ->leftJoin('user_account','user_account.user_id','=','users.id')
                ->leftJoIn("user_label_activity","user_label_activity.user_id","=","users.id")
                ->leftJoIn("user_label_activity_type","user_label_activity_type.id","=","user_label_activity.lable_id")
                ->leftJoin('member_ordinary', 'users.member', '=', 'member_ordinary.id')
                ->select($select_arr)
                ->first();
            $cc=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type = 3 and user_id=".$user->id);
                $bb=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type != 3 and user_id=".$user->id);
            $user->balance=$bb[0]->balance;
            $user->credit=$cc[0]->credit+$cc[0]->balance;
            //获取微信是否关注过
            $weixin_user = DB::select('select * from user_weixin_add where user_id = ' . $order->user_id);
            if(sizeof($weixin_user) > 0){
                $user->weixin_care = 1;
                // $user->head_img = $weixin_user[0]->avatar;
            }else{
                $user->weixin_care=0;
            }
            $uci=UserCarInfo::find($order->user_car_id);
            //查看是否有支付记录
            $opr = OrderPayRecord::where('order_id',$order_id)->where('status',1)->select('id')->get()->toArray();
            $user->OrderPay = !empty($opr)? TRUE : FALSE;
            //查看是否有套餐卡支付记录
            $scop = ServiceCardOrderPayRecord::where('order_id',$order_id)->where('status',1)->select('id')->get()->toArray();
            $user->ServiceCardOrderPay = !empty($scop) ? TRUE : FALSE;
            //是否使用了优惠卷
            $coi = CouponOrderInfo::where('order_id',$order_id)->where('status',1)->select('id')->get()->toArray();
            $user->CouponOrder = !empty($coi)? TRUE : FALSE;
            //是否是使用了企业套餐
            $op = OrderProduct::where('order_id',$order_id)->whereIn('product_type',['enterprise','service_card'])->where('status',1)->select('id')->get()->toArray();
            $user->OrderProduct = !empty($op) ? TRUE : FALSE;

            $member_dis         = isset($user->member_dis) ? $user->member_dis : '';                //会员折扣
            $experience         = isset($user->experience) ? $user->experience : '';                //会员经验值
            $member_level_name  = isset($user->member_level_name) ? $user->member_level_name : '';  //会员等级名称
            
            // if(is_null($uci)&&$order->order_type==1){//服务单才判断 3月13 取消该逻辑
            //     $response = Lang::get("scs_error.order_car_info_notexit_40001");
            //     break;
            // }
            $csi=DataCarStandardInfo::find($order->car_model_id);
            // if(is_null($csi)&&$order->order_type==1){ //服务单才判断 3月13 取消该逻辑
            //     $response = Lang::get("scs_error.order_car_model_notexit_40002");
            //     break;
            // }
            // $number=Orders::where("car_no",$msc->car_no)->whereIn("status",array(1216,1017,1117,1317,1018))->max("mileage");
            $car_arr=array(
                "car_no"=>$order->car_no,
                "kilometre"=>$order->mileage,
                "befor_kilometre"=>isset($uci)?$uci->mileage:0,
                "vin"=>isset($uci)?$uci->vin_code:"",
                "note"=>isset($uci)?$uci->note:"",
                "desc"=>isset($uci)?$uci->note:"",
                "brand_name"=>isset($csi)?$csi->brand_name:"",
                "brand_name_id"=>isset($csi)?$csi->brand_name_id:"",
                "series_name"=>isset($csi)?$csi->series_name:"",
                "series_name_id"=>isset($csi)?$csi->series_name_id:"",
                "model_name"=>isset($csi)?$csi->model_name:"",
                "model_id"=>isset($csi)?$csi->id:0,
                "user_car_id"=>$order->user_car_id,
                "insurance"=>isset($uci)?$uci->insurance:'',
                "start_off_time"=>isset($uci)?$uci->start_off_time:'',
            );
            $engineer_info=array();
            if($order->engineer_id != 0){
                $engineer_info=MaintenanceEngineers::where('id',$order->engineer_id)->where('type','shop')->select('id','name')->first();
            }
            $order->type=$user->type;
            if($user->type==2){//如果是企业用户
                $compnay=Companys::find($user->id);
                $order->company_name=isset($compnay)?$compnay->name:"";
                if($uci){
                    $ucd=UserCarDesc::find($uci->id);
                }                
                $order->card_no=isset($ucd) ? $ucd->card_no : "";
            }
            //计算 该用户订单消费金额
            $temp_order_amount = Orders::where("user_id",$user->id)->whereIn('status',array(1018,1017,1217,1317,1417))->sum("payable_amount");
            //计算该用户退款数量
            $temp_re_amount = ReturnOrder::leftJoin("orders","orders.order_id","=","return_order.order_id")
            ->where("orders.user_id",$user->id)->where("return_order.status",1)->sum("return_order.amount");
            $user->total_sale_amount=$temp_order_amount-$temp_re_amount;


            if($order->tittle=="先生"){
                $sex=1;
            }elseif($order->tittle=="女士"){
                $sex=2;
            }else{
                $sex=0;
            }
            $order->sex=$sex;

            //关联订单信息
            $or=OrderRelations::where('mirror_order_id',Input::get('order_id'))->first();
            $order->relation_order_id=isset($or->order_id) ? $or->order_id : '';
            $orderProduct=OrderProduct::getOrderProductById($order->order_id);
            $sc=SCUser::where('status',1)->where('shop_id',$sc_user->shop_id)->where('title',1)->select('id','real_name')->get();
            // $approvers=Config::get("order.discount_approvers");
            $temp_ca=CityAuthorization::where("city_id",$order->city)->where("discount",1)->where("status",1)->select("id","name")->get();
            
            if($order->car_no){
                $time=date("Y-m-d H:i:s",time());
                $cd=CarDiscount::where(function($query)use ($sc_user){
                        $query->where("shop_id",0)
                        ->orWhere('shop_id',$sc_user->shop_id);
                    })
                    ->where('car_no',$order->car_no)
                    ->where('start_time','<=',$time)
                    ->where('stop_time','>=',$time)
                    ->where('status',1)
                    ->OrderBy('created_at','desc')
                    ->first();
            }
            $arr=array();
            //CMS配置的长期折扣折扣
            $cd_arr['dis']=isset($cd->dis) ? $cd->dis :1;
            $cd_arr['created_at']=isset($cd->created_at) ? $cd->created_at :'';
            $cd_arr['relation']=isset($cd->relation) ? $cd->relation :'无';
            if(isset($cd->dis)){
                $cd_arr['type']=2;
            }else{
                $cd_arr['type']=0;
            }
            $arr[]=$cd_arr;
            if($order->car_no){
                $time=date("Y-m-d H:i:s",time());
                $cdp=CarDiscountPermanent::where('car_no',$order->car_no)->where('start_time','<=',$time)->where('end_time','>=',$time)->where('status',1)->first();
            }
            
            
            //临时折扣
            $cdt=CarDiscountTemp::where('status',1)->where('order_id',Input::get('order_id'))->first();
            $cdt_arr['dis']=isset($cdt->dis) ? $cdt->dis :1;
            $cdt_arr['created_at']=isset($cdt->created_at) ? $cdt->created_at :'';
            $cdt_arr['relation']=isset($cdt->relation) ? $cdt->relation :'无';
    	    if(isset($cdt->dis)){
                $cdt_arr['type']=1;
            }else{
                $cdt_arr['type']=0;
            }
            $arr[]=$cdt_arr;
            
            //申请长期折扣 -客户维护
            $cdp_arr['dis']=isset($cdp->dis) ? $cdp->dis :1;
            $cdp_arr['created_at']=isset($cdp->created_at) ? $cdp->created_at :'';
            $cdp_arr['relation']=isset($cdp->relation) ? $cdp->relation :'无';
    	    if(isset($cdp->dis)){
                $cdp_arr['type']=2;
            }else{
                $cdp_arr['type']=0;
            }
            $arr[]=$cdp_arr;
            
            
            //查看用户的会员体系级别
            if($order->user_id!=Config::get('config.linshou_id')&&$order->user_id!=1000000000){//不是特殊用户才有 会员信息
                //查找用户的套餐卡
                $now_member=MemberOrdinary::find($user->member);
                $now_data=UserMember::where("user_id",$user->id)->where("member",$user->member)->orderBy("created_at","desc")->first();
                $pt_member['dis']=isset($now_member->dis) ? $now_member->dis:1;
                $pt_member['created_at']=isset($now_data->created_at) ? $now_data->created_at :'';
                $pt_member['relation']='无';
                $pt_member['type']=3;
                $mtu_member = MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                        ->where("member_temporary_user.user_id",$user->id)
                        ->where("member_temporary_user.end_time",">",Common::currentTimeString())
                        ->orderBy("member_temporary.dis","asc")
                        ->select("member_temporary.dis","member_temporary.name","member_temporary_user.created_at")
                        ->first();
                $ls_member['dis']=isset($mtu_member->dis) ? $mtu_member->dis:1;
                $ls_member['created_at']=isset($mtu_member->created_at) ? $mtu_member->created_at :'';
                $ls_member['relation']='无';
                $ls_member['type']=4;
                
                if($pt_member['dis']<=$ls_member['dis']){
                    $arr[]=$pt_member;
                }else{
                    $arr[]=$ls_member;
                    $member_dis         = $ls_member['dis'];                                    //会员折扣
                    $experience         = '';                                                   //会员经验值
                    $member_level_name  = isset($mtu_member->name) ? $mtu_member->name : '';    //会员等级名称
                }
            }
            
            foreach($arr as $key=>$_arr){
                $dis[$key]=$_arr['dis'];  
                $created_at[$key]=$_arr['created_at'];  
            }
            array_multisort($dis, SORT_ASC, $created_at, SORT_DESC, $arr);
            $dis_arr=$arr[0];
            
            $dis_last['dis']=$dis_arr['dis'];
            $dis_last['relation']=$dis_arr['relation'];
            $dis_last['type']=$dis_arr['type'];
            $user->u_dis=$dis_arr['dis'];            
            //显示普通会员和临时会员中的 折扣最优的会员信息
            $user->member_dis = $member_dis;                //会员折扣      
            $user->experience = $experience;                //会员经验值
            $user->member_level_name = $member_level_name;  //会员等级名称
            
            //协助前段处理金钱价格
            $order->amount=$order->amount/100;
            $order->discount_amount=$order->discount_amount/100;
            $order->payable_amount=$order->payable_amount/100;
            $order->balance_amount=$order->balance_amount/100;
            $order->discount=$order->discount/100;
            $new_dl=DrivingLicenseNew::where("car_no",$order->car_no)->orderBy("updated_at","desc")->first();
            
            //订单支付记录
            $opr=OrderPay::where('order_id',Input::get('order_id'))->where('status',1)->select("id",'pay_type','amount','create_type','create_by','pay_id','tran_no')->get();
            $shop_amount=array();
            foreach ($opr as $_op) {
                if($_op->pay_type==8){//说明是余额支付// 找出这些余额使用那些支付
                    $arr=DB::select("
                        select sum(aursr.amount)/100 as amount,uad.account_no,ms.`name`,uad.acount_type from acount_user_recharge_spend_record aursr LEFT JOIN acount_user_recharge_record aurr on aurr.id=aursr.aurr_id 
                        LEFT JOIN maintenance_shops ms on ms.id=aurr.shop_id LEFT JOIN user_account_details uad on uad.account_no=aurr.account_no
                        where aursr.type=1 and aursr.buss_id=? GROUP BY uad.acount_type,uad.shop_id",array($_op->id));
                    foreach ($arr as $_arr) {
                        if(isset($shop_amount[$_arr->account_no])){
                            $shop_amount[$_arr->account_no]->amount=$shop_amount[$_arr->account_no]->amount+$_arr->amount;
                        }else{
                            $shop_amount[$_arr->account_no]=$_arr;
                        }
                    }
                }
            }
            $remind=$orderProduct['remind'];            
            unset($orderProduct['remind']);
            $temp_arr=array("order_info"=>$order,"user_car_info"=>$car_arr,"product_info"=>$orderProduct,"engineer_info"=>$engineer_info,"user_info"=>$user,"order_pay_record"=>$opr,'sc'=>$sc,'approvers'=>$temp_ca,'dis'=>$dis_last,"shop_amount"=>array_values($shop_amount),"new_dl"=>$new_dl,"remind"=>$remind);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
    	}while(false);
    	Log::info("info", array("system" => "scs" ,"event" => "order_show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-01-12 09:59:41
     * @Description: 创建订单
     */
    public function create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'max:50',
                'phone' => 'max:20',
                'agent_name' => 'required',
                'agent_sex' => 'required',
                'car_no'=>'required|max:20|alpha_dash',
                'car_model_id'=>'required',
                "mileage"=>'required|numeric',
                "vin"=>'required',
                "note"=>'max:100',
                "insurance"=>'date',
                "user_id"=>'required'
            ),
            $messages = array(
                'token.required' =>"token必填",
                'name.max' =>"姓名不能超过50字符",
                'phone.max' =>"电话必须11位数字",
                'agent_name.required' =>"送修人必填",
                'agent_sex.required' =>"送修性别必填",
                'car_no.required' =>"车牌号必填",
                'car_no.max' =>"车牌号必须小于20位",
                'car_no.alpha_dash' =>"车牌号不能包含特殊字符",
                'car_model_id.required' =>"车型必填",
                'mileage.required' =>"里程必填",
                'mileage.numeric' =>"里程必须输入数字",
                'vin.required' =>"VIN必须填",
                'note.max' =>"备注最多100个字",
                'insurance.date' =>"保险到期日必须是日期",
                'user_id.required' =>"用户必填",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["msg"]=$response["msg"].(implode(",",$validator->messages()->all()));
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            if(Orders::createOrderBefore(Input::get('car_no'),$sc_user->shop_id,1)){
                $response = Lang::get("scs_error.order_create_error_40066");
                break;
            }
            $csi=DataCarStandardInfo::find(Input::get("car_model_id"));
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            $user_id=Input::get('user_id');
            if($user_id!=0){
                $user=Users::find(Input::get('user_id'));
                if($user->status!=1){
                    $response = Lang::get("scs_error.order_cusuom_error_40004");
                    $response["result"]=$validator->messages()->all();
                    break;
                }
            }else{
                $user=Users::where("phone",Input::get("phone"))->first();
            }
            if($user){//如果存在用户判断用户
                if($user->status!=1){
                    $response = Lang::get("scs_error.order_cusuom_error_40004");
                    $response["result"]=$validator->messages()->all();
                    break;
                }
            }else{
                $user=new Users;
                $user->phone=Input::get("phone");
                $user->real_name=Input::get("name");
                $user->area=Input::get("area","010");
                $user->status=1;
                $user->register_source_id=14;//门店
                $user->member = Config::get('user.def_member');
                $user->sex=Input::get('sex');
                $user->save();
            }
            $uci=UserCarInfo::where("user_id",$user->id)->where("car_no",Input::get("car_no"))->where("status",1)->first();
            if($uci){//如果用户存在该车辆
                // if(Input::get('mileage')<$uci->mileage){//如果 这次保养的里程 小于
                //      $response = Lang::get("scs_error.order_mileage_error_40030");
                //      break;
                // }

                if($uci->is_lock==1){//如果是认证车辆
                    //修改其他车型不同的的认证车辆 认证状态为未认证
                    UserCarInfo::where("car_no",Input::get("car_no"))->where("is_lock",1)->where("car_model_id","!=",$csi->id)->update(array("is_lock"=>0));
                    UserCarInfo::where("id",$uci->id)->update(array("is_lock"=>1));
                    //修改认证车型信息
                    // $uci->is_lock=1;
                    // $uci->save();
                    $uacs=UserAuthenticationCar::where('car_no',$uci->car_no)->where('car_model_id',$csi->id)->where('status',1)->get();
                    if(!sizeof($uacs)){
                        UserAuthenticationCar::where("car_no",$uci->car_no)->update(array("status"=>0));
                        $uac=new UserAuthenticationCar();
                        $uac->status=1;
                        $uac->car_no=$uci->car_no;
                        $uac->vin_code=strtoupper(Input::get("vin"));
                        $uac->mileage=$uci->mileage;
                        $uac->car_brand_id=$csi->brand_name_id;
                        $uac->car_series_id=$csi->series_name_id;
                        $uac->car_model_id=$csi->id;
                        $uac->user_id=$uci->user_id;
                        $uac->shop_id=$sc_user->shop_id;
                        $uac->create_by=$sc_user->id;
                        $uac->shop_id=$sc_user->shop_id;
                        $uac->save();
                    }

                }

                ModifyCarsRecords::saveRecords($sc_user,$uci->id);

            }else{//如果不存在该车辆
                $uci=new UserCarInfo;
                $uci->car_no = strtoupper(Input::get('car_no'));
                $uci->user_id = $user->id;
                $uci->status = 1;
                $uci->is_default = 0;
                $uci->car_level = 0;
                $uci->is_lock = 0;
                $uci->mileage =0;//里程 为0 订单结束的是偶的时候更改用户的车辆里程
            }
            $uci->car_series_id = $csi->series_name_id;
            $uci->car_brand_id = $csi->brand_name_id;
            $uci->car_model_id = $csi->id;
            $uci->vin_code =strtoupper(Input::get("vin"));
            // $uci->mileage =0;//里程 为0 订单结束的是偶的时候更改用户的车辆里程
            $uci->note=Input::get("note");
            $uci->insurance=Input::get("insurance");
            $uci->start_off_time=Input::get("start_off_time");
            $uci->save();

            if(Input::get('agent_sex')==1){
                $tittle='先生';
            }elseif(Input::get('agent_sex')==2){
                $tittle='女士';
            }else{
                $tittle='保密';
            }
            $orders = new Orders();
            $order_id = Common::createOrderId();
            $orders->order_id = $order_id;
            $orders->user_id =$user->id;
            $orders->city = $sc_user->shop->city_id;
            $orders->place = 2;
            $orders->book_time =date("Y-m-d",time()) ;
            $orders->book_hour ="";
            $orders->shop_id = $sc_user->shop_id;
            $orders->address = "";
            $orders->name = Input::get("agent_name");
            $orders->tittle = $tittle;
            $orders->phone = Input::get("agent_phone",'无');
            $orders->pay_type = 0;
            $orders->user_car_id = $uci->id;
            $orders->amount = 0;
            $orders->work_service =0;
            $orders->status =1412;
            // $orders->note = Input::get("note","");
            $orders->note = Input::get("note")?Input::get("note"):"";
            $orders->car_brand_id = $csi->brand_name_id;
            $orders->car_brand_name = $csi->brand_name;
            $orders->car_series_id = $csi->series_name_id;
            $orders->car_series_name = $csi->series_name;
            $orders->car_model_id = $csi->id;
            $orders->car_model_name = $csi->model_name;
            $orders->car_no = $uci->car_no;
            $orders->outer_order_id = 0;
            $orders->engineer_id = 0;
            $orders->car_id = 0;
            $mileage=Input::get('mileage');
            if(isset($mileage)){
                $orders->mileage = Input::get('mileage')?Input::get('mileage'):0;
            }
            $orders->oil_meter = 0;
            $orders->order_source = 14;//门店
            $orders->product_comment = "";
            $orders->book_type = 2;
            $orders->reception_id = $sc_user->id;
            $orders->reception_name = $sc_user->real_name;
            $orders->save();

            //进入停车场
            $mp = new MaintenancePark();
            $mp->shop_id=$sc_user->shop_id;
            $mp->order_id=$order_id;
            $mp->status=3;
            $mp->user_id=$sc_user->id;
            $mp->save();

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order_id;
            $order_flows->status =1411;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order_id;
            $order_flows->status =1412;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();

            //记录行驶证信息
            try{
                if(Input::get('vin_code')!=""&&Input::get('car_no')!=""&&Input::get('send_time')!=""){
                    $dln=DrivingLicenseNew::where("car_no",Input::get('car_no'))->where("vin",Input::get('vin_code'))->where("send_time",Input::get('send_time'))->first();
                    if(is_null($dln)){//如果没有新建改记录
                        $dln=new DrivingLicenseNew();
                        $dln->shop_id = $sc_user->shop_id;
                        $dln->created_by=$sc_user->id;
                    }else{
                        $dln->updated_by=$sc_user->id;
                    }
                    if(Input::get('img')!="null"){
                        $dln->img = Input::get('img');
                    }                    
                    $dln->car_no = Input::get('car_no');
                    $dln->car_type = Input::get('car_type');
                    $dln->own = Input::get('own');
                    $dln->address = Input::get('address');
                    $dln->model = Input::get('model');
                    $dln->vin = strtoupper(Input::get("vin_code"));
                    $dln->engine_number = Input::get('engine_number');
                    $dln->register_time = Input::get('register_time');
                    $dln->send_time = Input::get('send_time');
                    $dln->use_nature = Input::get('use_nature');
                    if (empty($dln->is_lock)){ //$dln->is_lock == 1 锁定不允许修改
                        $dln->save();
                    }
                    
                    $dlo=new DrivingLicenseOrder();
                    $dlo->order_id=$order_id;
                    $dlo->license_id=$dln->id;
                    $dlo->created_by=$sc_user->id;
                    $dlo->save();
                    // $dls=DrivingLicenseShop::where("license_id",$dln->id)->where("shop_id",$sc_user->shop_id)->first();
                    // if(is_null($dls)){
                        $dls=new DrivingLicenseShop();
                        $dls->license_id=$dln->id;
                        $dls->shop_id=$sc_user->shop_id;
                        $dls->created_by=$sc_user->id;
                        $dls->save();
                    // }
                    // $dlu=DrivingLicenseUser::where("license_id",$dln->id)->where("user_id",$user->id)->first();
                    // if(is_null($dlu)){
                        $dlu=new DrivingLicenseUser();
                        $dlu->license_id=$dln->id;
                        $dlu->user_id=$user->id;
                        $dlu->created_by=$sc_user->id;
                        $dlu->save();
                    // }
                    $temp_uci=UserCarInfo::find("id",$uci->id);
                    $temp_uci->vin_code=strtoupper(Input::get("vin_code"));
                    if(Input::get('register_time')){
                         $temp_uci->start_off_time=Input::get('register_time');
                    }                   
                    $temp_uci->save();
                    if($temp_uci->is_lock==1){//如果是认证车辆                       
                        UserAuthenticationCar::where('car_no',$uci->car_no)->where('status',1)->update(array("vin_code"=>strtoupper(Input::get("vin_code"))));
                    }
                }
            }catch(Exception $e){
                ;
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      lyt
     * @DateTime:    2016-03-29 09:29:55
     * @Description: 修改订单的预计完成时间
     */
    public function orderDate(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'date'=>'required|date',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            if(strtotime(Input::get("date"))<time()){
                $response = Lang::get("scs_error.order_extime_error_40031");
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order) || $order->order_type==2){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($order->status,Orders::$orderStart)){//订单状态是正确
                $response = Lang::get("scs_error.order_status_error_40023");
                break;
            }
            $order->estimated_completion_time=Input::get("date");
            $order->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "orderDate", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-19 14:04:56
     * @Description: 订单的开工开工前判断是否有技师
     */
    public function orderStartBefore(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
    
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order) || $order->order_type==2){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($order->status,array(1112,1312,1412))){
                $response = Lang::get("scs_error.order_status_error_40064");
                break;
            }
            $msc=MaintenanceStationCar::where("shop_id",$sc_user->shop_id)->where("status",1)->where("car_no",$order->car_no)->first();
            if(strtotime($order->estimated_completion_time)<time()){
                $response = Lang::get("scs_error.order_extime_error_40031");
                break;
            }
            $station_id=$engineer_id=0;
            if($msc){
                $et=EngineerTokens::where("work_station_num",$msc->station_id)->orderBy("created_at","desc")->first();
                if($et){
                    $engineer_id=$et->engineer_id;
                }
                $station_id=$msc->station_id;
            }
            $mes=MaintenanceEngineers::where('status',1)->where('type','shop')->where('type_id',$sc_user->shop_id)->select('id','name')->get();
            $ms=MaintenanceStation::where('status',1)->where('shop_id',$sc_user->shop_id)->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("engineer_list"=>$mes,"login_engineer_id"=>$engineer_id,"ms"=>$ms,"station_id"=>$station_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "orderStartBefore", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zy
     * @DateTime:    2017-8-15 14:04:56
     * @Description: 返回当前门店技师列表
     */
    public function engineersList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $mes=MaintenanceEngineers::where('status',1)->where('type','shop')->where('type_id',$sc_user->shop_id)->select('id','name')->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("engineer_list"=>$mes));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "engineersList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    /**
     * @Author:      lyt
     * @DateTime:    2016-01-21 15:01:55
     * @Description: 订单的开工
     * @link http://www.activity.com/v1/scs/order/orderStart?token=8758c298265570bc0bd03443acb7ac48&order_id=15295610738896&engineer_id=338&station_id=6&reception_id=154
     */
    public function orderStart(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'engineer_id' => 'required',
                'station_id' => 'required',
                'reception_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $reception_id = Input::get('reception_id');     //接车前台id
            $reception_info = SCUser::find($reception_id);  //门店接车人信息
            if(is_null($reception_info) || $reception_info->status != 1){
                $response = Lang::get("scs_error.scs_user_isset_error_21019");
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order) || $order->order_type==2){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($order->status,Orders::$orderStart)){//订单状态是正确
                $response = Lang::get("scs_error.order_status_error_40023");
                break;
            }
            
            $me=MaintenanceEngineers::find(Input::get('engineer_id'));
            if($me->status!=1 || is_null($me)){
                $response = Lang::get("scs_error.engineer_error_22006");
                break;
            }
            if($me->type_id != $sc_user->shop_id){
                $response = Lang::get("scs_error.engineer_error_22007");
                break;
            }
            $uci=UserCarInfo::find($order->user_car_id);
            if(is_null($uci)){
                $response = Lang::get("scs_error.order_car_info_notexit_40001");
                break;
            }
            // if($order->mileage<$uci->mileage){//如果 这次保养的里程 小于
            //     $response = Lang::get("scs_error.order_mileage_error_40030");
            //     break;
            // }
            $csi=DataCarStandardInfo::find($uci->car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            if(Input::get('station_id')){
                $mscs_old=MaintenanceStationCarStatus::where('car_no',$order->car_no)->where('status',1)->first();
                $mscs_new=MaintenanceStationCarStatus::where('shop_id',$sc_user->shop_id)->where('station_id',Input::get('station_id'))->whereIn('status',array(1,2))->first();
                if($mscs_new){
                    if($mscs_old){
                        if($mscs_new->car_no != $mscs_old->car_no){
                            $response = Lang::get("scs_error.work_station_status_error_22008");
                            break;
                        }
                        MaintenanceStationCarStatus::where('shop_id',$sc_user->shop_id)->where('station_id',Input::get('station_id'))->update(array('status' => 2 ,'order_id'=>$order->order_id));
//                        //记录车辆进入工位时间（开始时间）
//                        $station_start_time = MaintenanceStationDetails::InsertDetails(Input::get('station_id'),$sc_user->shop_id);
//                        if(is_null($station_start_time)){
//                            $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                            break;
//                        }
//                        if($station_start_time == '0'){
//                            $response = Lang::get("sce_error.station_car_start_time_exiet_1002");
//                            break;
//                        }
//                        if($station_start_time == '1'){
//                            $response = Lang::get("sce_error.station_car_start_time_exiet_1003");
//                            break;
//                        }
//                        if($station_start_time == '3'){
//                            $response = Lang::get("sce_error.work_station_car_no_empty1014");
//                            break;
//                        }
//                        if($station_start_time == '4'){
//                            $response = Lang::get("sce_error.station_car_start_time_exiet_1004");
//                            break;
//                        }
                    }else{
                        $response = Lang::get("scs_error.work_station_status_error_22008");
                        break;
                    }
                }else{
                    if($mscs_old){
                        if($mscs_old->station_id !=  Input::get('station_id')){
                            MaintenanceStationCarStatus::where('shop_id',$sc_user->shop_id)->where('station_id',$mscs_old->station_id)->update(array('status' => 0 , 'car_no' => '',"car_model_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>'','order_id'=>'','start_off_time'=>''));
                            MaintenanceStationCarStatus::where('shop_id',$sc_user->shop_id)->where('station_id',Input::get('station_id'))->update(array('status' => 2 , 'car_no' => $order->car_no,"car_model_id"=>$order->car_model_id,'mileage'=>$order->mileage,'vin_code'=>$uci->vin_code,'insurance'=>$uci->insurance,'start_off_time'=>$uci->start_off_time,'order_id'=>$order->order_id));
                        }
                    }else{
                         MaintenanceStationCarStatus::where('shop_id',$sc_user->shop_id)->where('station_id',Input::get('station_id'))->update(array('status' => 2 , 'car_no' => $order->car_no,"car_model_id"=>$order->car_model_id,'mileage'=>$order->mileage,'vin_code'=>$uci->vin_code,'insurance'=>$uci->insurance,'start_off_time'=>$uci->start_off_time,'order_id'=>$order->order_id));
                    }
                }
                //记录车辆进入工位时间（开始时间）
                try {
                    $station_start_time = MaintenanceStationDetails::InsertDetails(Input::get('station_id'),$sc_user->shop_id);
                }catch(Exception $e){
                    Log::error("error", array("system" => "scs" ,"event" => "InsertDetails", 'input' =>Input::all() ,"exception" => $e));
                }

//                if(is_null($station_start_time)){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                    break;
//                }
//                if($station_start_time == '0'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1002");
//                    break;
//                }
//                if($station_start_time == '1'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1003");
//                    break;
//                }
//                if($station_start_time == '3'){
//                    $response = Lang::get("sce_error.work_station_car_no_empty1014");
//                    break;
//                }
//                if($station_start_time == '4'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1004");
//                    break;
//                }
                MaintenancePark::where('order_id',$order->order_id)->delete();
            }else{
                //入停车场记录
                $mp=MaintenancePark::where('order_id',$order->order_id)->first();
                if($mp){
                    $mp->status=4;
                    $mp->save();
                }else{
                    $mp = new MaintenancePark();
                    $mp->shop_id=$sc_user->shop_id;
                    $mp->order_id=Input::get('order_id');
                    $mp->status=4;
                    $mp->user_id=$sc_user->id;
                    $mp->save();
                }
                //工位占用详细信息入库(结束时间)
                try {
                    $station_start_time = MaintenanceStationDetails::UpdatedDetails($order->order_id,$sc_user->shop_id);
                }catch(Exception $e){
                    Log::error("error", array("system" => "scs" ,"event" => "UpdatedDetails", 'input' =>Input::all() ,"exception" => $e));
                }

//                if(is_null($station_start_time)){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                    break;
//                }
//                if($station_start_time == '0'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1002");
//                    break;
//                }
//                if($station_start_time == '1'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1003");
//                    break;
//                }
//                if($station_start_time == '4'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1004");
//                    break;
//                }
                MaintenanceStationCarStatus::where('order_id',Input::get('order_id'))->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>'','start_off_time'=>''));
            }
            if($uci->is_lock!=1){//如果该车以前不是认证车辆 修改该车为认证车辆
                //修改其他车型不同的的认证车辆 认证状态为未认证
                UserCarInfo::where("car_no",$uci->car_no)->where("is_lock",1)->where("car_model_id","!=",$csi->id)->update(array("is_lock"=>0));
                UserCarInfo::where("id",$uci->id)->update(array("is_lock"=>1));
               // $uci->is_lock=1;
               // $uci->save();
                $uacs=UserAuthenticationCar::where('car_no',$uci->car_no)->where('car_model_id',$csi->id)->where('status',1)->get();
                if(count($uacs)==0){
                    UserAuthenticationCar::where("car_no",$uci->car_no)->update(array("status"=>0));
                    $uac=new UserAuthenticationCar();
                    $uac->status=1;
                    $uac->car_no=$uci->car_no;
                    $uac->vin_code=$uci->vin_code;
                    $uac->mileage=$uci->mileage;
                    $uac->car_brand_id=$uci->car_brand_id;
                    $uac->car_series_id=$uci->car_series_id;
                    $uac->car_model_id=$uci->car_model_id;
                    $uac->user_id=$uci->user_id;
                    $uac->shop_id=$sc_user->shop_id;
                    $uac->create_by=$uci->create_by;
                    $uac->shop_id=$sc_user->shop_id;
                    $uac->save();
                }
            }
            $order->start_time=Common::num2DateTime(time(),"Y-m-d H:i:s");
            // $order->estimated_completion_time=Input::get("date");
            $order->engineer_id=Input::get('engineer_id');
            $order->status=1215;
            $order->reception_id = $reception_info->id;
            $order->reception_name = $reception_info->real_name;
            $order->save();

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order->order_id;
            $order_flows->status =1215;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();

            //删除该订单停车场信息
            //MaintenancePark::where('order_id',$order->order_id)->delete();

            //推送微信信息
            $wechat_user=Users::find($order->user_id);
            if(isset($wechat_user)&&$wechat_user->openid&&$order->order_type==1){
                $templateId = Config::get('config.scs_order_start_templateId');
                $url = Config::get('config.redirect_url').'/order/show?is_wash=0&order_id='.$order->order_id;
                $data = array(
                    "first"  => "亲爱的车主您好，你的爱车服务进度已更新。",
                    "keyword1" =>  $order->car_no,
                    "keyword2"   => "保养/维修",
                    "keyword3"   => "服务开始",
                    "remark" => "请点击查看详细检测记录"
                );
                try {
                    WechatOauthController::sendMessage($wechat_user->openid, $templateId, $data, $url);
                }catch(Exception $e){
                    Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                }
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zy
     * @DateTime:    2017-08-14 
     * @Description: 修改订单技师
     */
    public function updateEngineer(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'engineer_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order) || $order->order_type==2){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($order->status,Orders::$update_engineer)){//订单状态是正确
                $response = Lang::get("scs_error.order_status_error_40023");
                break;
            }
            $me=MaintenanceEngineers::find(Input::get('engineer_id'));
            if($me->status!=1 || is_null($me)){
                $response = Lang::get("scs_error.engineer_error_22006");
                break;
            }
            if($me->type_id != $sc_user->shop_id){
                $response = Lang::get("scs_error.engineer_error_22007");
                break;
            }

            $order->engineer_id=Input::get('engineer_id');
            $return_status = $order->save();
        }while(false);
        $response = array('code' => 0, 'msg' => 'ok', 'result' => $return_status);
        Log::info("info", array("system" => "scs" ,"event" => "updateEngineer", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-5-7 下午3:30
     * @Description:     修改订单的接车人信息
     * @param string $token     用户token
     * @param string $order_id  订单id
     * @param int $reception_id 接车前台id
     * @link http://api.anhui.com/v1/scs/order/updateReceptionInfo?token=38cf7a76ffc352f7e8249a9c77a80cca&order_id=15138459492023&reception_id=12
     */
    public function updateReceptionInfo(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'reception_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user = $this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id = Input::get('order_id', '');
            $reception_id = Input::get('reception_id', '');
            
            $order = Orders::find($order_id);
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id != $sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(in_array($order->status, Orders::$complete)){     //订单已完成
                $response = Lang::get("scs_error.order_status_error_40040");
                break;
            }
            $reception_info = SCUser::find($reception_id);  //门店接车人信息
            
            if(is_null($reception_info) || $reception_info->status != 1){
                $response = Lang::get("scs_error.scs_user_isset_error_21019");
                break;
            }
            if($reception_info->shop_id != $sc_user->shop_id){
                $response = Lang::get("scs_error.scs_user_isset_error_21019");
                break;
            }

            $order->reception_id = $reception_info->id;
            $order->reception_name = $reception_info->real_name;
            $return_status = $order->save();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $return_status);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "updateReceptionInfo", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-1-25 13:33:27
     * @Description: 修改订单支付金额
     */
    public function modifyAmount(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'user_name' => 'required',
                'password'  => 'required',
                'balance_amount' => 'required',
                'remark' => 'required'
            )
        );
        $user_name = Input::get('user_name');
        $password = SCUser::make(Input::get('password'));
        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $su = SCUser::where('user_name',$user_name)->where('password',$password)->first();
            if(!isset($su)){
                $response = Lang::get("scs_error.login_user_userpw_error_21003");
                break;
            }
            $order=Orders::find(Input::get('order_id'));

            //判断是否为店长
            if($su->title!=1){
                $response = Lang::get("scs_error.login_user_error_21007");
                break;
            }
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$su->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->order_type==1){//如果是服务单
                if(!in_array($order->status,array(1216,1420))){//订单状态是正确
                // if($order->status!=1216){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40024");
                    break;
                }

            }else{
                if($order->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            //查看时候有支付记录
            $op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }
            $op=OrderProduct::where('order_id',Input::get('order_id'))->where('product_type','enterprise')->where('status',1)->get();
            if(sizeof($op)>0){
                $response = Lang::get("scs_error.order_modify_error_40041");
                break;
            }
            $op=OrderProduct::where('order_id',Input::get('order_id'))->where('product_type','activity')->where('status',1)->get();
            if(sizeof($op)>0){
                $response = Lang::get("scs_error.order_modify_error_40094");
                break;
            }
            if($order->discount>0){
                $response = Lang::get("scs_error.order_modify_error_40061");
                break;
            }
            
            $opcr = new OrderPriceChangeRecords;
            $opcr->order_id=$order->order_id;
            $opcr->user_id=$sc_user->id;
            $opcr->amount=$order->balance_amount;
            $opcr->modify_amount=Input::get('balance_amount')*100;
            $opcr->save();

            $order->balance_amount=Input::get('balance_amount')*100;
            $order->save();

            $order_remark = new OrderRemark;
            $order_remark->order_id = $order->order_id;
            $order_remark->status =$order->status;
            $order_remark->remark ="修改价格为:".Input::get('balance_amount')." ".Input::get('remark');
            $order_remark->user_id = $su->id;
            $order_remark->user_type = 'sc';
            $order_remark->save();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_modifyAmount", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-24 16:52:28
     * @Description: 取消修改价格
     */
    public function cancelModifyAmount(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
    
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
    
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->order_type==1){//如果是服务单
                if(!in_array($order->status,array(1216,1420))){//订单状态是正确
                // if($order->status!=1216){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40024");
                    break;
                }
    
            }else{
                if($order->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            //查看时候有支付记录
            $op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }
            $discount_amount=is_null($order->discount_amount) ? 0 : $order->discount_amount;
            $opcr = new OrderPriceChangeRecords;
            $opcr->order_id=$order->order_id;
            $opcr->user_id=$sc_user->id;
            $opcr->amount=$order->balance_amount;
            $opcr->modify_amount=$order->amount-$discount_amount-$order->discount;
            $opcr->save();
    
            $order->balance_amount=$order->amount-$discount_amount-$order->discount;
            $order->save();
    
            $order_remark = new OrderRemark;
            $order_remark->order_id = $order->order_id;
            $order_remark->status =$order->status;
            $order_remark->remark ="取消修改价格:".(($order->amount-$discount_amount-$order->discount)/100);
            $order_remark->user_id = $sc_user->id;
            $order_remark->user_type = 'sc';
            $order_remark->save();
    
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_modifyAmount", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      lyt
     * @DateTime:    2016-06-07 09:40:56
     * @Description: 结算前的状态判断
     */
    public function confirmBefore(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            $userInfo=Users::find($order->user_id);
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }                        
            if($order->order_type==1){//如果是服务单
                if(isset($userInfo) && $userInfo->is_prior==0){
                    // if($order->status!=1216){//订单状态是否为服务结束状态
                    if(!in_array($order->status,array(1216,1420))){//订单状态是正确
                        $response = Lang::get("scs_error.order_status_error_40024");
                        break;
                    }
                }                
            }else{
                if($order->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            /*
            if(!MaintenanceOutOrder::isAllOut($order->order_id)){//是否有 没有出入库记录的耗材
                $response = Lang::get("scs_error.order_out_return_notexit_40035");
                break;
            }
            */

            if(Orders::isOutReturnOrders($order->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }
            $new_arr=array();
            $new_arr[]=$userInfo->u_dis;

            if($order->car_no){
                $time=date("Y-m-d H:i:s",time());
                $cd=CarDiscount::where(function($query)use ($sc_user){
                        $query->where("shop_id",0)
                        ->orWhere('shop_id',$sc_user->shop_id);
                    })
                    ->where('car_no',$order->car_no)
                    ->where('start_time','<=',$time)
                    ->where('stop_time','>=',$time)
                    ->where('status',1)
                    ->OrderBy('created_at','desc')
                    ->first();
            }
            $new_arr[]=isset($cd->dis) ? $cd->dis :1;
            // $arr=array();
            // //CMS配置的长期折扣折扣
            // $cd_arr['dis']=isset($cd->dis) ? $cd->dis :1;
            // $cd_arr['created_at']=isset($cd->created_at) ? $cd->created_at :'';
            // $cd_arr['relation']=isset($cd->relation) ? $cd->relation :'无';
            // if(isset($cd->dis)){
            //     $cd_arr['type']=2;
            // }
            // $arr[]=$cd_arr;
            if($order->car_no){
                $time=date("Y-m-d H:i:s",time());
                $cdp=CarDiscountPermanent::where('car_no',$order->car_no)->where('start_time','<=',$time)->where('end_time','>=',$time)->where('status',1)->first();
            }
            $new_arr[]=isset($cdp->dis) ? $cdp->dis :1;
            
            //临时折扣
            $cdt=CarDiscountTemp::where('status',1)->where('order_id',Input::get('order_id'))->first();
            $new_arr[]=isset($cdt->dis) ? $cdt->dis :1;
            // $cdt_arr['dis']=isset($cdt->dis) ? $cdt->dis :1;
            // $cdt_arr['created_at']=isset($cdt->created_at) ? $cdt->created_at :'';
            // $cdt_arr['relation']=isset($cdt->relation) ? $cdt->relation :'无';
            // if(isset($cdt->dis)){
            //     $cdt_arr['type']=1;
            // }
            // $arr[]=$cdt_arr;
            
            // //申请长期折扣 -客户维护
            // $cdp_arr['dis']=isset($cdp->dis) ? $cdp->dis :1;
            // $cdp_arr['created_at']=isset($cdp->created_at) ? $cdp->created_at :'';
            // $cdp_arr['relation']=isset($cdp->relation) ? $cdp->relation :'无';
            // if(isset($cdp->dis)){
            //     $cdp_arr['type']=2;
            // }
            // $arr[]=$cdp_arr;
            
            // foreach($arr as $key=>$_arr){
            //     $dis[$key]=$_arr['dis'];  
            //     $created_at[$key]=$_arr['created_at'];  
            // }
            if($order->user_id!=Config::get('config.linshou_id')&&$order->user_id!=1000000000){//不是特殊用户才有 会员信息
                //查找用户的套餐卡
                $now_member=MemberOrdinary::find($userInfo->member);
                $new_arr[]=isset($now_member->dis) ? $now_member->dis:1;
               
                
                $mtu_member=MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                ->where("member_temporary_user.user_id",$userInfo->id)->where("member_temporary_user.end_time",">",Common::currentTimeString())->orderBy("member_temporary.dis","asc")->select("member_temporary.dis","member_temporary_user.created_at")->first();    
                    
                $new_arr[]=isset($mtu_member->dis) ? $mtu_member->dis:1;
            }  
            asort($new_arr);
            $new_arr=array_values($new_arr);
            // array_multisort($dis, SORT_ASC, $created_at, SORT_DESC, $arr);
            // $dis_arr=$arr[0];
            // $dis=$dis_arr['dis'];
            $dis=round($new_arr[0],2);
            if($dis!=1.00){
                if(!Orders::isFitDiscount($order->order_id,$dis)){//是否有折扣权限
                    $response = Lang::get("scs_error.order_pay_error_40063");
                    break;
                }
            }else{
                $dis=0.9;
                if(!Orders::isFitDiscount($order->order_id,$dis)){//是否有折扣权限
                    $response = Lang::get("scs_error.order_pay_error_40065");
                    break;
                }
            }
            $response['result']=array('order_id'=>$order->order_id);
            $response=MaintenanceOutOrder::outNum($order->order_id);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "confirmBefore", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-8-15 11:51:19
     * @Description: 结算前创建用户
     */
    public function createUser(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'name' => 'required',
                'sex' => 'required',
                'phone' => 'required',
            ),
            $messages = array(
                'token.required' =>"token必填",
                'order_id.required' =>"订单号必填",
                'name.required' =>"姓名必填",                
                'sex.required' =>"性别必填",
                'phone.required' => '电话必填',
            )
        );    
        $response = array('code' => 0, 'msg' => 'ok');
    
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["msg"]=$response["msg"].(implode(",",$validator->messages()->all()));
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            //查看时候有支付记录
            $op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }
            
            //查看是否有支付记录
            $opr = OrderPayRecord::where('order_id',$order->order_id)->where('status',1)->select('id')->get()->toArray();
            if(!empty($opr)){
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }
            //查看是否有套餐卡支付记录
            // $scop = ServiceCardOrderPayRecord::where('order_id',$order->order_id)->where('status',1)->select('id')->get()->toArray();
            // if(!empty($scop)){
            //     $response = Lang::get("scs_error.service_card_order_pay_record_40112");
            //     break;
            // }
            //是否使用了优惠卷
            $coi = CouponOrderInfo::where('order_id',$order->order_id)->where('status',1)->select('id')->get()->toArray();
            if(!empty($coi)){
                $response = Lang::get("scs_error.coupon_order_info_40112");
                break;
            }
            //是否是使用了企业套餐
            $OrderProduct = OrderProduct::where('order_id',$order->order_id)->whereIn('product_type',['enterprise','service_card'])->where('status',1)->select('id')->get()->toArray();
            if(!empty($OrderProduct)){
                $response = Lang::get("scs_error.order_product_40112");
                break;
            }
            
            $csi=DataCarStandardInfo::find($order->car_model_id);
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
           // if($order->user_id!=1000000000){
           //     $response = Lang::get("scs_error.order_error_40058");
           //     break;
           // }
            $user=Users::where("phone",Input::get("phone"))->first();
            if($user){//如果存在用户判断用户
                if($user->status!=1){
                    $response = Lang::get("scs_error.order_cusuom_error_40060");
                    $response["result"]=$validator->messages()->all();
                    break;
                }else if($user->type==1){
                    $user->real_name=Input::get('name');
                    $user->sex=Input::get('sex');
                    $user->save();
                }
            }else{
                $user=new Users;
                $user->phone=Input::get("phone");
                $user->real_name=Input::get("name");
                $user->area=Input::get("area","010");
                $user->status=1;
                $user->register_source_id=14;//门店
                $user->member = Config::get('user.def_member');
                $user->sex=Input::get('sex');
                $user->save();
            }
            $uci=UserCarInfo::where("user_id",$user->id)->where("car_no",$order->car_no)->where("status",1)->first();
            $userCarInfo=UserCarInfo::where('user_id',$order->user_id)->where('car_no',$order->car_no)->where('status',1)->first();
            if($uci){//如果用户存在该车辆
                if($uci->is_lock==1){//如果是认证车辆
                    UserCarInfo::where("car_no",Input::get("car_no"))->where("is_lock",1)->where("car_model_id","!=",$csi->id)->update(array("is_lock"=>0));
                    UserCarInfo::where("id",$uci->id)->update(array("is_lock"=>1));
                    $uacs=UserAuthenticationCar::where('car_no',$uci->car_no)->where('car_model_id',$csi->id)->where('status',1)->get();
                    if(!sizeof($uacs)){
                        UserAuthenticationCar::where("car_no",$uci->car_no)->update(array("status"=>0));
                        $uac=new UserAuthenticationCar();
                        $uac->status=1;
                        $uac->car_no=$uci->car_no;
                        $uac->vin_code=strtoupper(Input::get("vin"));
                        $uac->mileage=$uci->mileage;
                        $uac->car_brand_id=$csi->brand_name_id;
                        $uac->car_series_id=$csi->series_name_id;
                        $uac->car_model_id=$csi->id;
                        $uac->user_id=$uci->user_id;
                        $uac->shop_id=$sc_user->shop_id;
                        $uac->create_by=$sc_user->id;
                        $uac->shop_id=$sc_user->shop_id;
                        $uac->save();
                    }
            
                }
                ModifyCarsRecords::saveRecords($sc_user,$uci->id);
            }else{//如果不存在该车辆
                UserCarInfo::where("car_no",$order->car_no)->where("is_lock",1)->where("car_model_id","!=",$csi->id)->update(array("is_lock"=>0));
                $uacs=UserAuthenticationCar::where('car_no',$order->car_no)->where('car_model_id',$csi->id)->where('status',1)->get();
                // UserCarInfo::where("id",$uci->id)->update(array("is_lock"=>1));
                if(!sizeof($uacs)){
                    UserAuthenticationCar::where("car_no",$userCarInfo->car_no)->update(array("status"=>0));
                    $uac=new UserAuthenticationCar();
                    $uac->status=1;
                    $uac->car_no=$userCarInfo->car_no;
                    $uac->vin_code=$userCarInfo->vin_code;
                    $uac->mileage=$userCarInfo->mileage;
                    $uac->car_brand_id=$csi->brand_name_id;
                    $uac->car_series_id=$csi->series_name_id;
                    $uac->car_model_id=$csi->id;
                    $uac->user_id=$user->id;
                    $uac->shop_id=$sc_user->shop_id;
                    $uac->create_by=$sc_user->id;
                    $uac->shop_id=$sc_user->shop_id;
                    $uac->save();
                }
                $uci=new UserCarInfo;
                $uci->car_no = $order->car_no;
                $uci->user_id = $user->id;
                $uci->status = 1;
                $uci->is_default = 0;
                $uci->car_level = 0;
                $uci->is_lock = 1;
                $uci->mileage =0;//里程 为0 订单结束的是偶的时候更改用户的车辆里程
            }
            $uci->car_series_id = $userCarInfo->car_series_id;
            $uci->car_brand_id = $userCarInfo->car_brand_id;
            $uci->car_model_id = $userCarInfo->car_model_id;
            $uci->vin_code = $userCarInfo->vin_code;
            $uci->note=$userCarInfo->note;
            $uci->insurance=$userCarInfo->insurance;
            $uci->save();
            
            if(!$order->phone||$order->phone=="无"){
                $order->phone=$user->phone;
                $order->name=$user->real_name;
            }
            $order->user_id=$user->id;
            $order->user_car_id=$uci->id;
            $order->save();
            $dlo=DrivingLicenseOrder::where("order_id",$order->order_id)->orderBy("created_at","desc")->first();//如果 该订单有行驶证关联
            if(!is_null($dlo)){               
                $dlu=DrivingLicenseUser::where("license_id",$dlo->license_id)->where("user_id",$order->user_id)->first();//看看新用户是否已经有关系了 如果有 不新建
                if(is_null($dlu)){
                    $dlu=new DrivingLicenseUser();
                    $dlu->license_id=$dlo->license_id;
                    $dlu->user_id=$order->user_id;
                    $dlu->created_by=$sc_user->id;
                    $dlu->save();
                }
            } 
            $response =array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "confirmBefore", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      zwh
     * @DateTime:    2016-1-25 14:08:24
     * @Description: 确认结算
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-06-14 14:55:12
     * @Description: 确认结算功能调整 只是一个转换状态的 功能
     *注释掉 pay相关代码 零售单 不添加该状态判断
     */
    public function confirmPayment(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                // 'pays'=>"required",
                // 'amount' => 'required',
                // 'pay_type' => 'required'
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            $userInfo=Users::find($order->user_id);
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->order_type==1){//如果是服务单
                if(isset($userInfo) && $userInfo->is_prior==0){
                    if($order->status!=1216){//订单状态是否为服务结束状态
                        $response = Lang::get("scs_error.order_status_error_40024");
                        break;
                    }
                }                
            }else{//如果零售单 不允许执行 
                // if($order->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                // }
            }
            if(!MaintenanceOutOrder::isAllOut($order->order_id)){//是否有 没有出入库记录的耗材
                $response = Lang::get("scs_error.order_out_return_notexit_40035");
                break;
            }
            if(Orders::isOutReturnOrders($order->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }
            if(in_array($order->status,array(1117,1217,1417))){//是否已结算
                $response = Lang::get("scs_error.order_status_error_40040");
                break;
            }
            /*6月 
                S10版本注释 新确认订单逻辑 增加订单结算状态
            */
            $order_flows = new OrderFlows;
            $order_flows->order_id = $order->order_id;
            $order_flows->status =1420;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();
            $order->status=1420;
            $order->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));   
            /*6月 
                S10版本注释 取消支付相关 支付单独支付
            */
            // $pays = json_decode(Input::get('pays'),1);
            // $pay_array=array();
            // $pay_type=array();
            // $temp_amount=0;
            // foreach ($pays as $_pay) {
            //     $date_id=explode(":",$_pay);
            //     if($date_id[1]>=1000000){
            //         $response = Lang::get("scs_error.order_amount_error_40095");
            //         break 2;
            //     }
            //     $temp_amount+=$date_id[1];
            //     $pay_array[]=array("pay_type"=>$date_id[0],"amount"=>$date_id[1]);
            //     $pay_type[]=$date_id[0];
            // }
            
            // if(in_array(10,$pay_type) && sizeof($pay_type)>1){//不记账结算不可用于复合结算
            //     $response = Lang::get("scs_error.order_pay_type_error_40042");
            //     break;
            // }
            // $amount=$order->amount-$order->discount_amount;
            // //是否修改过订单支付金额
            // $temp_balance_anount=$order->balance_amount>0?$order->balance_amount:0;
            // if(floor($temp_balance_anount/100)!=$temp_amount){
            //     $response = Lang::get("scs_error.order_amount_error_40010");
            //     break;
            // }
            
            // //订单支付 记录账务
            // $response=Orders::pay($order->order_id,$pay_array,$sc_user->id,"sc",1417);
            // if($response["code"]!=0){
            //     break;
            // }

            // //更改用户车辆里程
            // if($order->order_type==1){
            //     $uci=UserCarInfo::find($order->user_car_id);
            //     ModifyCarsRecords::saveRecords($sc_user,$uci->id);
            //     $uci->mileage =$order->mileage;//
            //     $uci->save();
            // }
            // //订单反算金额
            // Orders::inverseOrder($order->order_id);

            // $order_flows = new OrderFlows;
            // $order_flows->order_id = $order->order_id;
            // $order_flows->status =1417;
            // $order_flows->user_id = $sc_user->id;
            // $order_flows->type = 'sc';
            // $order_flows->save();


            // if($order->order_type==1){//如果是 服务单 才有下面的逻辑
            //     //删除订单停车场记录
            //     MaintenancePark::where('order_id',Input::get('order_id'))->delete();

            //     //腾出车位
            //     $mscs=MaintenanceStationCarStatus::where('order_id',Input::get('order_id'))->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>'','start_off_time'=>''));
            //     $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));


            //     /*发送短信*/
            //     //SendMessage::sendSms('custom_pay_order_status',$order->order_id);

            //     /*邀请完成订单送券*/
            //     Coupons::invite($order->order_id);
            //     Coupons::payCoupon($order->order_id);
            // }
            
            
            // //推送微信信息
            // $wechat_user=Users::find($order->user_id);
            // if(isset($wechat_user)&&$wechat_user->openid){
            //     $templateId = Config::get('config.scs_order_end_templateId');
            //     $url = Config::get('config.redirect_url').'/order/show?order_id='.$order->order_id;
            //     $data = array(
            //         "first"  => "亲爱的车主您好，您预约的保养/维修服务已完成！",
            //         "keyword1" =>  $order->car_no." 保养/维修",
            //         "keyword2"   => $sc_user->shop->name,
            //         "keyword3"   => $order->book_time." ".$order->book_hour,
            //         "remark" => "感谢您使用安惠车服！评价服务10个字以上还可获得优惠券哦，赶紧行动吧！"
            //     );
            //     try {
            //         WechatOauthController::sendMessage($wechat_user->openid, $templateId, $data, $url);
            //     }catch(Exception $e){
            //         Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
            //     }
            // }
            /*6月 
                S10版本注释 取消支付相关 支付单独支付
            */
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_confirmPayment", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-06-14 15:34:12
     * @Description: 订单的支付信息
     */
    public function order_paydesc(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->order_type==1){//如果是服务单
                if($order->status!=1420){//订单状态是否为服务结束状态
                    $response = Lang::get("scs_error.order_status_error_40024");
                    break;
                }       
            }else{
                if($order->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $user_id=$order->pay_user_id==0?$order->user_id:$order->pay_user_id;
            $user=Users::where("id",$user_id)
                ->leftJoin('user_account','user_account.user_id','=','users.id')
                ->select('users.id','users.phone','users.register_source_id','users.real_name','users.sex','users.type','user_account.account_no','user_account.balance','user_account.credit','users.u_dis')
                ->first();
            $cc=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type = 3 and user_id=".$user->id);
            $bb=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type != 3 and user_id=".$user->id);
            $user->balance=$bb[0]->balance;
            $user->credit=$cc[0]->credit+$cc[0]->balance;
            $user->balance_amount=$order->balance_amount;
            $user->payable_amount=$order->payable_amount;

            $opr=OtherPayRecord::where("order_id",$order->order_id)->first();
            if($opr){
                $uci=UserCarInfo::find($opr->user_car_id);
            }else{
                $uci=UserCarInfo::find($order->user_car_id);
            }
            $user->car_no=isset($uci)?$uci->car_no:"";
            //订单支付记录
            $opr=OrderPay::where('order_id',$order->order_id)->whereIn('status',array(0,1,5,6,7))->select('id','status','pay_type','amount','create_type','create_by','pay_id','tran_no',"sources")->get();
            $opr_amount=OrderPay::where('order_id',$order->order_id)->where('status',5)->sum("amount");
            $user->payin_amount=$opr_amount;
            $temp_arr=array("user_info"=>$user,"order_pay_record"=>$opr);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_paydesc", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-06-15 12:57:49
     * @Description: 订单支付
     * 
     */
    public function order_pay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'pay_type' => 'required',
                'amount' => 'required',
                'source' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->order_type==1){//如果是服务单
                if($order->status!=1420){//订单状态是否为服务结束状态
                    $response = Lang::get("scs_error.order_status_error_40024");
                    break;
                }       
            }else{
                if($order->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            if(!isset(OrderPay::$pay_pay_type[Input::get("pay_type")])||!in_array(Input::get("source"),OrderPay::$pay_pay_type_source[Input::get("pay_type")])){
                $response = Lang::get("scs_error.order_pay_type_error_40096");
                break;
            }           

            $response = Orders::order_pay($order->order_id,Input::get("pay_type"),Input::get("amount"),$sc_user->id,"sc",Input::get("driver_id"),Input::get("source"));
            // $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_pay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-06-15 16:43:43
     * @Description: 取消订单支付记录
     * #link：
     */
    public function cancel_order_pay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->order_type==1){//如果是服务单
                if($order->status!=1420){//订单状态是否为服务结束状态
                    $response = Lang::get("scs_error.order_status_error_40024");
                    break;
                }       
            }else{
                if($order->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::find(Input::get("id"));
            if($op->order_id!=$order->order_id){
                $response = Lang::get("scs_error.order_pay_error_40120");
                break;
            }
            
            if($op->status==5){//说明是支付中
                $response = OrderPay::cancelPayIn($order->order_id,$op->id);
            }else if($op->status==1){
                //时间判断
                if(in_array($op->pay_type, array(2,3))&&$op->sources==2){
                    $response = Lang::get("scs_error.aur_undo_type_error_40126");
                    break;
                }
                if(date("Y-m-d",strtotime($op->implement_time))!=date("Y-m-d",time())){
                    $response = Lang::get("scs_error.order_time_error_40115");
                    break;
                }
                $response = OrderPay::cancel($order->order_id,$op->id,$sc_user->id,"sc");


            }else if($op->status==7){//说明是撤销中
                $response = OrderPay::cancelCanceIn($order->order_id,$op->id,$sc_user->id,"sc");
            }else{
                $response = Lang::get("scs_error.order_pay_error_40120");
                break;
            }            
            // $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_pay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-06-15 14:23:52
     * @Description: 完成订单接口
     * @link：http://www.activity.com/v1/scs/order/end_order?token=1d9dccc74de0de62b4578ff931e9a886&order_id=15295610738896
     */
    public function end_order(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }

            if(floor($order->balance_amount/100)!=floor($order->payable_amount/100)){
                $response = Lang::get("scs_error.order_pay_record_40114");
                break;
            }
            // if(bcsub($order->balance_amount,$order->payable_amount,0)>0){
            //     $response = Lang::get("scs_error.order_pay_record_40114");
            //     break;
            // }
            //如果没有任何成功支付记录不让结算 0元也要添加 0元支付记录
            $op=OrderPay::where("order_id",$order->order_id)->where("status",1)->first();   
            if(is_null($op)){
                $response = Lang::get("scs_error.order_pay_record_40114");
                break;
            }
            $opu=OrderPayUndo::where("order_id",$order->order_id)->where("status",0)->first();   
            if($opu){
                $response = Lang::get("scs_error.order_pay_record_40114");
                break;
            }

            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->user_id!=$order->pay_user_id){//如果是代付 支付用户不一致
                //验证身份
                if(Input::get('type')==1){
                    $sc=SCUser::find(Input::get('id'));
                    if(is_null($sc)){
                        $response = Lang::get("scs_error.order_otherpay_checkuser_error_42002");
                        break;
                    }
                    //判断验证码是否存在
                    $record = UserCheckCodeUpgrade::where('business_id',Input::get("order_id"))->where("business_type","other_pay")->where("phone",$sc->phone)->first();
                    if(is_null($record)){ //没有记录
                        $response = Lang::get("error.user_login_checkcode_null_1012");
                        break;
                    }               
                    if( time() > Common::datetime2Num($record->out_time_at) ){ //校验是否超过时限
                        $response = Lang::get("error.user_login_checkcode_timeout_1013");
                        break;
                    }       
                   
                    if($record->check_code != Input::get('code')){ //校验验证码是否匹配
                        $response = Lang::get("error.user_login_checkcode_error_1014");
                        break;
                    }
                }else{
                    $sc=SCUser::where('user_name',Input::get('username'))->where('password',strtoupper(md5(Input::get('password'))))->where('status',1)->first();
                    if(is_null($sc)){
                        $response = Lang::get("scs_error.scs_user_not_exiet21009");
                        break;
                    }                    
                }
                if($sc->title!=1){
                    $response = Lang::get("scs_error.order_otherpay_checkuser_error_42003");
                    break;
                }
            }
            if($order->order_type==1){//如果是服务单
                if($order->status!=1420){//订单状态是否为服务结束状态
                    $response = Lang::get("scs_error.order_status_error_40024");
                    break;
                }       
            }else{
                if($order->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            if(!MaintenanceOutOrder::isAllOut($order->order_id)){//是否有 没有出入库记录的耗材
                $response = Lang::get("scs_error.order_out_return_notexit_40035");
                break;
            }
            if(Orders::isOutReturnOrders($order->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }
            if(in_array($order->status,array(1117,1217,1417))){//是否已结算
                $response = Lang::get("scs_error.order_status_error_40040");
                break;
            }
            //更改用户车辆里程
            if($order->order_type==1){
                $uci=UserCarInfo::find($order->user_car_id);
                ModifyCarsRecords::saveRecords($sc_user,$uci->id);
                $uci->mileage =$order->mileage;//
                $uci->save();
            }
            //订单反算金额
            Orders::inverseOrder($order->order_id);

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order->order_id;
            $order_flows->status =1417;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();
            $order->pay_time=date("Y-m-d H:i:s",time()+Config::get("config.report_time_diff"));
            $order->status=1417;
            $order->save();
            ServiceCardDetailPack::endOrder($order->order_id);
            if($order->order_type==1){//如果是 服务单 才有下面的逻辑

                //工位占用详细信息入库(结束时间)
                try {
                    $station_start_time = MaintenanceStationDetails::UpdatedDetails($order->order_id,$sc_user->shop_id);
                }catch(Exception $e){
                    Log::error("error", array("system" => "scs" ,"event" => "UpdatedDetails", 'input' =>Input::all() ,"exception" => $e));
                }

//                if(is_null($station_start_time)){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                    break;
//                }
//                if($station_start_time == '0'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1002");
//                    break;
//                }
//                if($station_start_time == '1'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1003");
//                    break;
//                }
//                if($station_start_time == '4'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1004");
//                    break;
//                }

                //计算订单金额
                MaintenanceStationDetails::payable_amount($order->order_id,$sc_user->shop_id,$order->payable_amount);

                    //删除订单停车场记录
                MaintenancePark::where('order_id',Input::get('order_id'))->delete();

                //腾出车位
                $mscs=MaintenanceStationCarStatus::where('order_id',Input::get('order_id'))->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>'','start_off_time'=>''));
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));


                /*发送短信*/
                //SendMessage::sendSms('custom_pay_order_status',$order->order_id);

                /*邀请完成订单送券*/
                Coupons::invite($order->order_id);
                Coupons::payCoupon($order->order_id);
                Coupons::InvitationCoupon($order->user_id);
            }
            
            
            //推送微信信息
            $wechat_user=Users::find($order->user_id);
            if(isset($wechat_user)&&$wechat_user->openid&&$order->order_type==1){
                $templateId = Config::get('config.scs_order_end_templateId');
                $url = Config::get('config.redirect_url').'/order/show?is_wash=0&order_id='.$order->order_id;
                $data = array(
                    "first"  => "亲爱的车主您好，您预约的保养/维修服务已完成！",
                    "keyword1" =>  $order->car_no." 保养/维修",
                    "keyword2"   => $sc_user->shop->name,
                    "keyword3"   => $order->book_time." ".$order->book_hour,
                    "remark" => "感谢您使用安惠车服！评价服务10个字以上还可获得优惠券哦，赶紧行动吧！"
                );
                try {
                    WechatOauthController::sendMessage($wechat_user->openid, $templateId, $data, $url);
                }catch(Exception $e){
                    Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                }
            }


            //用户积分经验返还
            $temp_amount=OrderPay::where("order_id",$order->order_id)->where("status",1)->whereIn("pay_type",OrderPay::$ei_pay_type)->sum("amount");
            if($temp_amount>0){
                $temp_order=$order->order_type==1?1:2;
                $mc=MemberCoefficient::where("source",$temp_order)->where("status",1)->first();
                $ms=MaintenanceShops::find($sc_user->shop_id);

                UserIntegralFlow::record($order->pay_user_id,$sc_user->shop_id,$order->order_id,1,$order->order_type==1?1001:1002,floor($temp_amount*$mc->integral*$ms->integral/100),'订单完成积分');
                UserExperienceFlow::record($order->pay_user_id,$sc_user->shop_id,$order->order_id,1,$order->order_type==1?1001:1002,floor($temp_amount*$mc->experience*$ms->experience/100),'订单完成经验');
                Users::checkMember($order->pay_user_id);
            }
            
            //积分经验返还完成
            
            
            //套餐卡短信 和微信推送
            $temp_ser=OrderProduct::where("order_id",$order->order_id)->where("status",1)->where("product_type","service_card")->get();
            $temp_packarr=array();
            foreach ($temp_ser as $_ts) {
                if(isset($temp_packarr[$_ts->product_id])){ 
                    $temp_packarr[$_ts->product_id]["num"]=$temp_packarr[$_ts->product_id]["num"]+1;
                }else{
                    $temp_packarr[$_ts->product_id]=array("pack_id"=>$_ts->product_id,"num"=>1);
                }
            }
            if(sizeof($temp_packarr)>0)
                Users::checkServiceCardPack($order->order_id,$order->user_id,array_values($temp_packarr),$order->car_no,$sc_user->shop->name,$order->pay_time,0);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "end_order", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-06-16 11:00:45
     * @Description: 订单回到服务结束
     */
    public function return_serverend(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            $op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            } 
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }            
            if($order->order_type==1){//如果是服务单
                if($order->status!=1420){//订单状态是否为服务结束状态
                    $response = Lang::get("scs_error.order_status_error_40024");
                    break;
                }       
            }else{//零售单 不用这个接口
                $response = Lang::get("scs_error.order_status_error_40022");
                break;
            }

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order->order_id;
            $order_flows->status =1216;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();
            $order->status=1216;
            $order->save();

            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "return_serverend", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      lyt
     * @DateTime:  2017-06-16 11:13:47
     * @Description: 订单结束恢复到结算提车
     */
    public function return_confirmBefore(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }           
            if($order->status!=1417){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_status_error_40024");
                break;
            }  
            $ro=ReturnOrder::where("order_id",$order->order_id)->where("status","!=",2)->first();
            if($ro){
                $response = Lang::get("scs_error.order_return_error_40124");
                break;
            }
            $op=OrderPay::where("order_id",$order->order_id)->where("status",1)->orderBy("implement_time","desc")->first();      
            if(is_null($op)||date("Y-m-d",strtotime($op->implement_time))!=date("Y-m-d",time())){
                $response = Lang::get("scs_error.order_time_error_40119");
                break;
            }         
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "return_confirmBefore", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-06-16 11:13:47
     * @Description: 订单状态撤回
     * @param string $token         用户token
     * @param string $order_id      订单id
     * @param string $remark        撤回原因
     * @param int $type             授权方式 [1:动态授权;]
     * @param int $manager_id       店长id
     * @param string $sms_code      短信验证码
     * @link http://api.anhui.com/v1/scs/order/return_confirm?token=38b8ea29bc973529477253c773f9b745&manager_id=155&order_id=15355127383717&remark=撤回原因&type=1&id=155&sms_code=2574
     */
    public function return_confirm(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'remark' => 'required',
                'type' => 'required',
                'manager_id' => 'required',
                'sms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $order_id   = Input::get('order_id');   //订单id
            $remark     = Input::get('remark');     //撤回原因
            $type       = Input::get('type');       //授权方式 [1:动态授权;]
            $manager_id = Input::get('manager_id'); //店长id
            $sms_code   = Input::get('sms_code');   //短信验证码
            
            $user_info = SCUser::find($manager_id); //获取店长信息
            if(!$user_info){
                $response = Lang::get('scs_error.user_error_21009');
                break;
            }
            
//            if($type == 1){ //动态授权
//                
//            }
            //获取动态授权的验证码 
            $record = UserCheckCodeUpgrade::where('business_id', $order_id)
                    ->where('business_type', 'withdraw_order')
                    ->where('phone', $user_info->phone)
                    ->first();
            //判断验证码是否存在
            if(is_null($record)){ //没有记录
                $response = Lang::get("error.user_login_checkcode_null_1012");
                break;
            }
            //校验是否超过时限
            if( time() > Common::datetime2Num($record->out_time_at) ){
                $response = Lang::get("error.user_login_checkcode_timeout_1013");
                break;
            }
            //校验验证码是否匹配
            if($record->check_code != $sms_code){
                $response = Lang::get("error.user_login_checkcode_error_1014");
                break;
            }
            
            $order = Orders::find($order_id);   //获取订单信息详情
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }           
            if($order->status!=1417){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_status_error_40024");
                break;
            }
            $ro=ReturnOrder::where("order_id",$order->order_id)->where("status","!=",2)->first();
            if($ro){
                $response = Lang::get("scs_error.order_return_error_40124");
                break;
            }
            $op=OrderPay::where("order_id",$order->order_id)->where("status",1)->orderBy("implement_time","desc")->first();      
            if(is_null($op)||date("Y-m-d",strtotime($op->implement_time))!=date("Y-m-d",time())){
                $response = Lang::get("scs_error.order_time_error_40119");
                break;
            }

            $coupon_order=CouponOrderInfo::where('order_id',$order->order_id)->where('status',0)->where('val_status',1)->get();//获取所有 验证未使用优惠券
            foreach ($coupon_order as $_co) {
                $coupon=Coupons::find($_co->coupon_id);
                if($coupon->status==2){
                    $coupon->status=3;
                    $coupon->save();
                }else{
                    $_co->status=0;
                    $_co->val_status=0;
                    $_co->save();
                }
            }

            if($order->order_type==1){//如果是服务单
                //积分抵扣
                $temp_amount=OrderPay::where("order_id",$order->order_id)->where("status",1)->whereIn("pay_type",OrderPay::$ei_pay_type)->sum("amount");
                if($temp_amount>0){
                    $mc=MemberCoefficient::where("source",1)->where("status",1)->first();
                    $ms=MaintenanceShops::find($sc_user->shop_id);

                    UserIntegralFlow::record($order->pay_user_id,$sc_user->shop_id,$order->order_id,2,3001,floor($temp_amount*$mc->integral*$ms->integral/100),'订单撤回扣除积分');
                    UserExperienceFlow::record($order->pay_user_id,$sc_user->shop_id,$order->order_id,2,3001,floor($temp_amount*$mc->experience*$ms->experience/100),'订单撤回扣除经验');
                    Users::checkMember($order->pay_user_id);
                }
                
                //积分抵扣完毕
                $order_flows = new OrderFlows;
                $order_flows->order_id = $order->order_id;
                $order_flows->status =1420;
                $order_flows->user_id = $sc_user->id;
                $order_flows->type = 'sc';
                $order_flows->save();
                $order->status=1420;
                $order->save();    

                MaintenancePark::where('order_id',$order->order_id)->delete();

                $mp = new MaintenancePark();
                $mp->shop_id=$sc_user->shop_id;
                $mp->order_id=$order->order_id;
                $mp->status=1;
                $mp->user_id=0;
                $mp->save();
                
                //记录订单备注信息
                $order_remark_res = OrderRemark::addOrderRemarkInfo($order_id, 'sc', $sc_user->id, $remark, '1420');
            }else{//零售单 不用这个接口
                $status = 1411;
                $order_flows = new OrderFlows;
                $order_flows->order_id = $order->order_id;
                $order_flows->status =1411;
                $order_flows->user_id = $sc_user->id;
                $order_flows->type = 'sc';
                $order_flows->save();
                $order->status=1411;
                $order->save();    
                
                //记录订单备注信息
                $order_remark_res = OrderRemark::addOrderRemarkInfo($order_id, 'sc', $sc_user->id, $remark, '1411');
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "return_serverend", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-1-26 15:47:59
     * @Description: 导出出库单（）
     */

    /**
     * @Author:      lyt
     * @DateTime:  2017-08-01 14:48:29
     * @Description: 废弃方法 暂时关闭 测试 17/8/1
     */
    // public function maintenanceOutOrders(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //             'token' => 'required',
    //             'order_id' => 'required',
    //             'order_product_id' => 'required',
    //         )
    //         );
    //     $response = array('code' => 0, 'msg' => 'ok');

    //     do{
    //         if($validator->fails()) {
    //             $response = Lang::get("scs_error.args_error_10000");
    //             $response["result"]=$validator->messages()->all();
    //             break;
    //         }
    //         $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
    //         if(is_null($sc_user)){
    //             break;
    //         }
    //         $op=OrderProduct::find(Input::get('order_product_id'));
    //         $order=Orders::find(Input::get('order_id'));
    //         if(is_null($order)){
    //             $response = Lang::get("scs_error.order_notexiet_40000");
    //             break;
    //         }
    //         if($op->status === 0){
    //             $response = Lang::get("scs_error.order_delete_40017");
    //             break;
    //         }
    //         if($op->order_id != Input::get('order_id')){
    //             $response = Lang::get("scs_error.order_product_error_40016");
    //             break;
    //         }
    //         if($order->shop_id!=$sc_user->shop_id){
    //             $response = Lang::get("scs_error.order_note_shop_error_40003");
    //             break;
    //         }
    //         if($order->order_type==1){
    //             if(!in_array($order->status,Orders::$serviceStart)){//订单状态是正确
    //                 $response = Lang::get("scs_error.order_status_error_40029");
    //                 break;
    //             }
    //         }else{
    //             if($order->status!=1411){//订单状态是正确
    //                 $response = Lang::get("scs_error.order_status_error_40029");
    //                 break;
    //             }
    //         }
    //         //判断是否已生成过出库单
    //         if(Orders::isOutOrders(Input::get('order_id'),Input::get('order_product_id'))){
    //             $response = Lang::get("scs_error.order_out_error_40018");
    //             break;
    //         }
    //         if($op->product_type=='promotion'){
    //             $opp=OrderProduct::getOrderPromotionProductPackage(Input::get('order_id'),Input::get('order_product_id'));
    //             Orders::saveMaintenanceOutOrder($opp,'promotion',Input::get('order_id'),$sc_user->shop_id);
    //         }else if($op->product_type=='base'){
    //             $opi=OrderProduct::getOrderProductItemBase(Input::get('order_id'),Input::get('order_product_id'));
    //             Orders::saveMaintenanceOutOrder($opi,'base',Input::get('order_id'),$sc_user->shop_id);
    //         }else if($op->product_type=='non_standard'){
    //             $ons=OrderProduct::getOrderProductNonStandard(Input::get('order_id'),Input::get('order_product_id'));
    //             if($ons){
    //                 Orders::saveMaintenanceOutOrder($ons,'non_standard',Input::get('order_id'),$sc_user->shop_id);
    //             }
    //         }
    //         $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
    //     }while(false);
    //     Log::info("info", array("system" => "scs" ,"event" => "order_confirmPayment", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }

    /**
     * @Author:      zwh
     * @DateTime:    2016-1-26 15:47:59
     * @Description: 导出出库单（）
     */
    public function maintenanceOutOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'type' => 'required',
                'order_product_item_id' => 'required',
            )
            );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $type=Input::get('type');
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->order_type==1){
                if(!in_array($order->status,Orders::$serviceStart)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40029");
                    break;
                }
            }else{
                if($order->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40029");
                    break;
                }
            }
            //判断是否已生成过出库单
            if(Orders::isOutOrder(Input::get('order_id'),Input::get('order_product_item_id'),Input::get('type'))){
                $response = Lang::get("scs_error.order_out_error_40018");
                break;
            }
            if($type=='promotion'){
                $opi=OrderProductItem::find(Input::get('order_product_item_id'));
                if($opi){
                    if($opi->order_id != Input::get('order_id')){
                        $response = Lang::get("scs_error.order_out_error_40015");
                        break;
                    }
                    // //判断是否已生成过出库单
                    // if(Orders::isOutOrder(Input::get('order_id'),Input::get('order_product_item_id'),Input::get('type'))){
                    //     $response = Lang::get("scs_error.order_out_error_40018");
                    //     break;
                    // }
                    if($opi->type!=1){
                        $response = Lang::get("scs_error.order_out_error_40019");
                        break;
                    }
                    if($opi->num<=0){
                        $response = Lang::get("scs_error.order_out_num_error_40033");
                        break;
                    }
                    $ware_ = MaintenanceWarehouse::where('shop_id',$order->shop_id)->where('item_id',$opi->item_id)->select('number')->first();
                    if($ware_) {
                        $ware_num = $ware_->number;
                        if ($opi->num > $ware_num) {
                            $response = Lang::get("scs_error.maintenance_mw_number_60011");
                            break;
                        }
                    }else{
                        $response = Lang::get("scs_error.maintenance_mw_number_60011");
                        break;
                    }
                    $mop=new MaintenanceOutOrder();
                    $mop->shop_id=$sc_user->shop_id;
                    $mop->status=0;
                    $mop->type=0;
                    $mop->product_type=$type;
                    $mop->item_id=$opi->item_id;
                    $mop->product_item_id=$opi->id;
                    $mop->number=$opi->num;
                    $mop->order_id=$opi->order_id;
                    $mop->save();
                }
            }else if($type=='enterprise'){
                    $opesi=OrderProductEsItem::where('id',Input::get('order_product_item_id'))->lockForUpdate()->first();
                    if($opesi){
                        $opep=OrderProductEsPackage::find($opesi->order_product_package_id);
                        $op=OrderProduct::find($opep->order_product_id);
                        if($op->status!=1){
                            $response = Lang::get("scs_error.order_product_status_error_40009");
                            break;
                        }
                        if($opesi->order_id != Input::get('order_id')){
                            $response = Lang::get("scs_error.order_out_error_40015");
                            break;
                        }
                       
                        if($opesi->type!=1){
                            $response = Lang::get("scs_error.order_out_error_40019");
                            break;
                        }
                        if($opesi->num<=0){
                            $response = Lang::get("scs_error.order_out_num_error_40033");
                            break;
                        }
                        if($opesi->is_adapter==2){
                            $response = Lang::get("scs_error.order_out_num_error_40069");
                            break;
                        }
                        $ware_ = MaintenanceWarehouse::where('shop_id',$order->shop_id)->where('item_id',$opesi->item_id)->select('number')->first();
                        if($ware_) {
                            $ware_num = $ware_->number;
                            if ($opesi->num > $ware_num) {
                                $response = Lang::get("scs_error.maintenance_mw_number_60011");
                                break;
                            }
                        }else{
                            $response = Lang::get("scs_error.maintenance_mw_number_60011");
                            break;
                        }
                        $mop=new MaintenanceOutOrder();
                        $mop->shop_id=$sc_user->shop_id;
                        $mop->status=0;
                        $mop->type=$opesi->item_type;
                        $mop->product_type=$type;
                        $mop->item_id=$opesi->item_id;
                        $mop->product_item_id=$opesi->id;
                        $mop->number=$opesi->num;
                        $mop->order_id=$opesi->order_id;
                        $mop->save();
                    }
            }else if($type=='activity'){
                $opaci=OrderProductAcItem::where('id',Input::get('order_product_item_id'))->lockForUpdate()->first();
                if($opaci){
                    $opep=OrderProductAcPackage::find($opaci->order_product_package_id);
                    $op=OrderProduct::find($opep->order_product_id);
                    if($op->status!=1){
                        $response = Lang::get("scs_error.order_product_status_error_40009");
                        break;
                    }
                    if($opaci->order_id != Input::get('order_id')){
                        $response = Lang::get("scs_error.order_out_error_40015");
                        break;
                    }
                    //判断是否已生成过出库单
                    // if(Orders::isOutOrder(Input::get('order_id'),Input::get('order_product_item_id'),Input::get('type'))){
                    //     $response = Lang::get("scs_error.order_out_error_40018");
                    //     break;
                    // }
                    if($opaci->type!=1){
                        $response = Lang::get("scs_error.order_out_error_40019");
                        break;
                    }
                    if($opaci->num<=0){
                        $response = Lang::get("scs_error.order_out_num_error_40033");
                        break;
                    }
                    if($opaci->is_adapter==2){
                        $response = Lang::get("scs_error.order_out_num_error_40069");
                        break;
                    }
                    $ware_ = MaintenanceWarehouse::where('shop_id',$order->shop_id)->where('item_id',$opaci->item_id)->select('number')->first();
                    if($ware_) {
                        $ware_num = $ware_->number;
                        if ($opaci->num > $ware_num) {
                            $response = Lang::get("scs_error.maintenance_mw_number_60011");
                            break;
                        }
                    }else{
                        $response = Lang::get("scs_error.maintenance_mw_number_60011");
                        break;
                    }
                    $mop=new MaintenanceOutOrder();
                    $mop->shop_id=$sc_user->shop_id;
                    $mop->status=0;
                    $mop->type=$opaci->item_type;
                    $mop->product_type=$type;
                    $mop->item_id=$opaci->item_id;
                    $mop->product_item_id=$opaci->id;
                    $mop->number=$opaci->num;
                    $mop->order_id=$opaci->order_id;
                    $mop->save();
                }        
            }else if($type=='base'){
                $opbi=OrderProductBaseItem::where('id',Input::get('order_product_item_id'))->lockForUpdate()->first();
                if($opbi){
                    $op=OrderProduct::find($opbi->order_product_package_id);
                    if($op->status!=1){
                        $response = Lang::get("scs_error.order_product_status_error_40009");
                        break;
                    }
                    if($opbi->order_id != Input::get('order_id')){
                        $response = Lang::get("scs_error.order_out_error_40015");
                        break;
                    }
                    //判断是否已生成过出库单
                    // if(Orders::isOutOrder(Input::get('order_id'),Input::get('order_product_item_id'),Input::get('type'))){
                    //     $response = Lang::get("scs_error.order_out_error_40018");
                    //     break;
                    // }
                    if($opbi->type!=1){
                        $response = Lang::get("scs_error.order_out_error_40019");
                        break;
                    }
                    if($opbi->num<=0){
                        $response = Lang::get("scs_error.order_out_num_error_40033");
                        break;
                    }
                    if($opbi->is_adapter==2){
                        $response = Lang::get("scs_error.order_out_num_error_40069");
                        break;
                    }
                    $ware_ = MaintenanceWarehouse::where('shop_id',$order->shop_id)->where('item_id',$opbi->item_id)->select('number')->first();
                    if($ware_) {
                        $ware_num = $ware_->number;
                        if ($opbi->num > $ware_num) {
                            $response = Lang::get("scs_error.maintenance_mw_number_60011");
                            break;
                        }
                    }else{
                        $response = Lang::get("scs_error.maintenance_mw_number_60011");
                        break;
                    }
                    $mop=new MaintenanceOutOrder();
                    $mop->shop_id=$sc_user->shop_id;
                    $mop->status=0;
                    $mop->type=$opbi->item_type;
                    $mop->product_type=$type;
                    $mop->item_id=$opbi->item_id;
                    $mop->product_item_id=$opbi->id;
                    $mop->number=$opbi->num;
                    $mop->order_id=$opbi->order_id;
                    $mop->save();
                }
            }else if($type=='non_standard'){
                $opns=OrderProductNonStandard::where('id',Input::get('order_product_item_id'))->where('status',1)->lockForUpdate()->first();
                if($opns){
                    $op=OrderProduct::find($opns->order_product_id);
                    if($op->status!=1||$opns->status!=1){
                        $response = Lang::get("scs_error.order_product_status_error_40009");
                        break;
                    }
                    if($opns->order_id != Input::get('order_id')){
                        $response = Lang::get("scs_error.order_out_error_40015");
                        break;
                    }
                    //判断是否已生成过出库单
                    // if(Orders::isOutOrder(Input::get('order_id'),Input::get('order_product_item_id'),Input::get('type'))){
                    //     $response = Lang::get("scs_error.order_out_error_40018");
                    //     break;
                    // }
                    if($opns->service_type!=1){
                        $response = Lang::get("scs_error.order_out_error_40019");
                        break;
                    }
                    if($opns->num<=0){
                        $response = Lang::get("scs_error.order_out_num_error_40033");
                        break;
                    }
                    $ware_ = MaintenanceWarehouse::where('shop_id',$order->shop_id)->where('item_id',$opns->item_id)->select('number')->first();
                    if($ware_) {
                        $ware_num = $ware_->number;
                        if ($opns->num > $ware_num) {
                            $response = Lang::get("scs_error.maintenance_mw_number_60011");
                            break;
                        }
                    }else{
                        $response = Lang::get("scs_error.maintenance_mw_number_60011");
                        break;
                    }
                    $mop=new MaintenanceOutOrder();
                    $mop->shop_id=$sc_user->shop_id;
                    $mop->status=0;
                    $mop->type=$opns->type;
                    $mop->product_type=$type;
                    $mop->item_id=$opns->item_id;
                    $mop->product_item_id=$opns->id;
                    $mop->number=$opns->num;
                    $mop->order_id=$opns->order_id;
                    $mop->save();
                }
            }else if($type=='service_card'){
                $opsci=OrderProductScItem::where('id',Input::get('order_product_item_id'))->lockForUpdate()->first();
                if($opsci){
                    $op=OrderProduct::find($opsci->order_product_id);
                    if($op->status!=1){
                        $response = Lang::get("scs_error.order_product_status_error_40009");
                        break;
                    }
                    if($opsci->order_id != Input::get('order_id')){
                        $response = Lang::get("scs_error.order_out_error_40015");
                        break;
                    }
                    if($opsci->type!=1){
                        $response = Lang::get("scs_error.order_out_error_40019");
                        break;
                    }
                    if($opsci->num<=0){
                        $response = Lang::get("scs_error.order_out_num_error_40033");
                        break;
                    }
                    if($opsci->is_adapter==2){
                        $response = Lang::get("scs_error.order_out_num_error_40069");
                        break;
                    }
                    $ware_ = MaintenanceWarehouse::where('shop_id',$order->shop_id)->where('item_id',$opsci->item_id)->select('number')->first();
                    if($ware_) {
                        $ware_num = $ware_->number;
                        if ($opsci->num > $ware_num) {
                            $response = Lang::get("scs_error.maintenance_mw_number_60011");
                            break;
                        }
                    }else{
                        $response = Lang::get("scs_error.maintenance_mw_number_60011");
                        break;
                    }
                    $mop=new MaintenanceOutOrder();
                    $mop->shop_id=$sc_user->shop_id;
                    $mop->status=0;
                    $mop->type=$opsci->item_type;
                    $mop->product_type=$type;
                    $mop->item_id=$opsci->item_id;
                    $mop->product_item_id=$opsci->id;
                    $mop->number=$opsci->num;
                    $mop->order_id=$opsci->order_id;
                    $mop->save();
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_confirmPayment", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-3-5 10:33:32
     * @Description: 返回订单当前状态
     */
    public function returnStatus(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required'
            )
            );
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok','result'=>array('status'=>$orders->status,'order_type'=>$orders->order_type,"place"=>$orders->place));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "returnStatus", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-3-7 14:46:39
     * @Description: 订单取消
     */
    public function cancelOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'desc' => 'required|max:100',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->order_type==2){
                if($order->status!=1411){
                    $response = Lang::get("scs_error.order_status_error_40025");
                    break;
                }
                if(!MaintenanceOutOrder::isOutExist($order->order_id)){//是否存在已出库的耗材，终止订单需要全部退货后可终止
                    $response = Lang::get("scs_error.order_stop_error_40040");
                    break;
                }
                if(Orders::isOutReturnOrders($order->order_id)){//是否有 未完成的出退库 记录
                    $response = Lang::get("scs_error.order_out_return_error_40034");
                    break;
                }
            }else{
                if(!in_array($order->status, Orders::$cancancel_status)){
                    $response = Lang::get("scs_error.order_status_error_40025");
                    break;
                }
            }

            //如果是预约订单去除库存的 操作
            $om=OrderMaintence::find($order->order_id);
            if($om&&$om->status==1){
                if($om->maintenance_type=="shop"){//说明是门店库存
                    ShopStockOrder::where("stock_date",$om->boot_date)->where("time_part_id",$om->time_prat_id)->where("shop_id",$om->maintenance_id)->decrement('stock_current');
                }else{
                    $ctp=CarTimePart::where("car_id",$om->maintenance_id)->where("time_part_id",$om->time_prat_id)->first();
                    if($ctp){
                        CarStockOrder::where("stock_date",$om->boot_date)->where("time_part_id",$ctp->id)->where("car_id",$om->maintenance_id)->decrement('stock_current');
                    }
                }
            }
            //取消订单
            $order->status=1410;
            $order->save();
            $order_flows = new OrderFlows;
            $order_flows->order_id = Input::get('order_id');
            $order_flows->status =1410;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();

            $or=new OrderRemark;
            $or->order_id=$order->order_id;
            $or->user_type="sc";
            $or->user_id=$sc_user->id;
            $or->remark="取消订单：".Input::get("desc");
            $or->status=1410;
            $or->save();
            ServiceCardDetailPack::cancelOrder($order->order_id);//回退套餐卡

            //工位占用详细信息入库(结束时间)
            try {
                $station_start_time = MaintenanceStationDetails::UpdatedDetails(Input::get('order_id'),$sc_user->shop_id);
            }catch(Exception $e){
                Log::error("error", array("system" => "scs" ,"event" => "UpdatedDetails", 'input' =>Input::all() ,"exception" => $e));
            }


            // 删除订单停车场记录
            MaintenancePark::where('order_id',Input::get('order_id'))->delete();

            //腾出车位
            $mscs=MaintenanceStationCarStatus::where('order_id',Input::get('order_id'))->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>'','start_off_time'=>''));
            Coupons::returnCoupon($order->order_id);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancelOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      lyt
     * @DateTime:    2016-06-07 17:38:30
     * @Description: Description
     */
    public function stopOrderBefore(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)|| $order->order_tyoe==2){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($order->status, Orders::$stop_order)){//订单状态是否为服务开始或结束
                $response = Lang::get("scs_error.order_status_error_40024");
                break;
            }
            if(!MaintenanceOutOrder::isOutExist($order->order_id)){//是否存在已出库的耗材，终止订单需要全部退货后可终止
                $response = Lang::get("scs_error.order_stop_error_40040");
                break;
            }
            if(Orders::isOutReturnOrders($order->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }

            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
            // }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "stopOrderBefore", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-3-7 15:11:49
     * @Description: 终止订单
     * @param string $token         用户token
     * @param string $order_id      订单id
     * @param string $remark        原因说明
     * @param int $type             授权方式 [1:动态授权;]
     * @param int $id               店长id
     * @param string $code          短信验证码
     * @link：http://api.anhui.com/v1/scs/order/stopOrder?token=875887b2a901f93106aeccf16fae2f8b&order_id=15299981118654&remark=穷&type=1&id=155&code=1234
     */
    public function stopOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                //'pays'=>"required",
                'remark'  => 'required',
                'type'  => 'required',
                'id'  => 'required',
                'code'  => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $order_id   = Input::get('order_id');   //订单id
            $remark     = Input::get('remark');     //撤回原因
            $type       = Input::get('type');       //授权方式 [1:动态授权;]
            $id         = Input::get('id');         //店长id
            $code       = Input::get('code');       //短信验证码
            
            $user_info = SCUser::find($id); //获取店长信息
            if(!$user_info){
                $response = Lang::get('scs_error.user_error_21009');
                break;
            }
            
//            if($type == 1){ //动态授权
//                
//            }
            //获取动态授权的验证码 
            $record = UserCheckCodeUpgrade::where('business_id', $order_id)
                    ->where('business_type', 'stop_order')
                    ->where('phone', $user_info->phone)
                    ->first();
            //判断验证码是否存在
            if(is_null($record)){ //没有记录
                $response = Lang::get("error.user_login_checkcode_null_1012");
                break;
            }
            //校验是否超过时限
            if( time() > Common::datetime2Num($record->out_time_at) ){
                $response = Lang::get("error.user_login_checkcode_timeout_1013");
                break;
            }
            //校验验证码是否匹配
            if($record->check_code != $code){
                $response = Lang::get("error.user_login_checkcode_error_1014");
                break;
            }
            
            $order = Orders::find($order_id);
            if(is_null($order) || $order->order_tyoe==2){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($order->status, Orders::$stop_order)){//订单状态是否为服务开始或结束
                $response = Lang::get("scs_error.order_status_error_40024");
                break;
            }
            if(!MaintenanceOutOrder::isOutExist($order->order_id)){//是否存在已出库的耗材，终止订单需要全部退货后可终止
                $response = Lang::get("scs_error.order_stop_error_40040");
                break;
            }
            if(Orders::isOutReturnOrders($order->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }

            //$pays = json_decode(Input::get('pays'),1);
            //$pay_array=array();
            //$temp_amount=0;
            //foreach ($pays as $_pay) {
            //    $date_id=explode(":",$_pay);
            //    $temp_amount+=$date_id[1];
            //    $pay_array[]=array("pay_type"=>$date_id[0],"amount"=>$date_id[1]);
            //}




            //$amount=$order->amount-$order->discount_amount;
            //是否修改过订单支付金额
            // if($order->balance_amount>0){
            //$temp_balance_anount=$order->balance_amount>0?$order->balance_amount:0;
            //if(floor($temp_balance_anount/100)!=$temp_amount){
            //    $response = Lang::get("scs_error.order_amount_error_40010");
            //    break;
            //}

            // }else{
            //     if($amount/100!=Input::get('amount')){
            //         $response = Lang::get("scs_error.order_amount_error_40010");
            //         break;
            //     }
            // }
            


            //订单支付 记录账务
            //$response=Orders::pay($order->order_id,$pay_array,$sc_user->id,"sc",1419);
            //if($response["code"]!=0){
            //    break;
            //}

            //更改用户车辆里程
            //$uci=UserCarInfo::find($order->user_car_id);
            //$uci->mileage =$order->mileage;//
            //$uci->save();

            // $order->payable_amount=Input::get('amount')*100;
            // $order->pay_type=Input::get('pay_type');
            // $order->status=1419;
            // $order->pay_time=date("Y-m-d H:i:s",time());
            // $order->save();
            // /*记录账务*/
            // $response = Account::pending_order($order->order_id);
            // if($response['code'] == 0){
             $order->status=1419;
            // $order->pay_time=date("Y-m-d H:i:s",time()+Config::get("config.report_time_diff"));
             $order->save();

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order->order_id;
            $order_flows->status =1419;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();

            $order_remark = new OrderRemark;
            $order_remark->order_id = $order->order_id;
            $order_remark->status =1419;
            $order_remark->remark =Input::get('remark');
            $order_remark->user_id = $sc_user->id;
            $order_remark->user_type = 'sc';
            $order_remark->save();
            
            //记录订单备注信息
            $order_remark_res = OrderRemark::addOrderRemarkInfo($order_id, 'sc', $sc_user->id, $remark, '1419');
            
            ServiceCardDetailPack::cancelOrder($order->order_id);//回退套餐卡
            //返还优惠券
            Coupons::returnCoupon($order->order_id);

            //删除订单停车场记录
            MaintenancePark::where('order_id',Input::get('order_id'))->delete();

            //记录车辆占用工位结束时间
            try {
                $station_start_time = MaintenanceStationDetails::UpdatedDetails($order->order_id,$sc_user->shop_id);
            }catch(Exception $e){
                Log::error("error", array("system" => "scs" ,"event" => "UpdatedDetails", 'input' =>Input::all() ,"exception" => $e));
            }

//            if(is_null($station_start_time)){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                break;
//            }
//            if($station_start_time == '0'){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1002");
//                break;
//            }
//            if($station_start_time == '1'){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1003");
//                break;
//            }
//            if($station_start_time == '4'){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1004");
//                break;
//            }


            //腾出车位
            $mscs=MaintenanceStationCarStatus::where('order_id',Input::get('order_id'))->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>'','start_off_time'=>''));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));


            /*发送短信*/
            //SendMessage::sendSms('custom_pay_order_status',$order->order_id);

            /*邀请完成订单送券*/
            //Coupons::invite($order->order_id);
            // }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_stopOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-3-7 17:28:15
     * @Description: 维修记录
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-08-01 15:13:47
     * @Description: 暂时废弃 不用 注释
     */
    // public function maintenanceRecords(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //             'token' => 'required',
    //             'order_id' => 'required',
    //         )
    //         );
    //     $response = array('code' => 0, 'msg' => 'ok');
    //     do{
    //         if($validator->fails()) {
    //             $response = Lang::get("scs_error.args_error_10000");
    //             $response["result"]=$validator->messages()->all();
    //             break;
    //         }
    //         $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
    //         if(is_null($sc_user)){
    //             break;
    //         }
    //         $order=Orders::find(Input::get('order_id'));
    //         if(is_null($order)){
    //             $response = Lang::get("scs_error.order_notexiet_40000");
    //             break;
    //         }
    //         if($order->shop_id!=$sc_user->shop_id){
    //             $response = Lang::get("scs_error.order_note_shop_error_40003");
    //             break;
    //         }
    //         $order_ids=Orders::where("car_no",$order->car_no)->whereIn("status",Orders::$complete)->select('order_id')->get()->toArray();
    //         $orderProduct=OrderProduct::getOrderProductByOrderId($order_ids);
    //         $temp_arr=array("product_info"=>$orderProduct);
    //         $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
    //     }while(false);
    //     Log::info("info", array("system" => "scs" ,"event" => "maintenanceRecords", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }

    /**
     * @Author:      zwh
     * @DateTime:    2016-3-8 16:20:51
     * @Description: 检测记录
     */
    public function checkRecords(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            $o3c=Order30Check::where('order_id',Input::get('order_id'))->where('object_id','!=','general_suggest')->get();
            $suggest=Order30Check::where('order_id',Input::get('order_id'))->where('object_id','general_suggest')->first();
            $error=Order30Check::where('order_id',Input::get('order_id'))->where('status',1)->where('object_id','!=','general_suggest')->get();
            $order_ring_check=OrderRingCheck::find(Input::get('order_id'));
            if(is_null($order_ring_check)){
                $result = array(
                    'order_id' => Input::get('order_id'),
                    'sound' => 0,
                    'cigarette_lighter' => 0,
                    'front_mark' => 0,
                    'tire_cover' => 0,
                    'rear_mark' => 0,
                    'axle_cover' => 0,
                    'antenna' => 0,
                    'fire_extinguisher' => 0,
                    'fuel' => 0,
                    'mile' => 0,
                    'note' => '',
                    'pic' => ''
                );
            }else{
                $path=Config::get('config.ring_check_img_url');
                $result = array(
                    'order_id' => Input::get('order_id'),
                    'sound' => $order_ring_check->sound,
                    'cigarette_lighter' => $order_ring_check->cigarette_lighter,
                    'front_mark' => $order_ring_check->front_mark,
                    'tire_cover' => $order_ring_check->tire_cover,
                    'rear_mark' => $order_ring_check->rear_mark,
                    'axle_cover' => $order_ring_check->axle_cover,
                    'antenna' => $order_ring_check->antenna,
                    'fire_extinguisher' => $order_ring_check->fire_extinguisher,
                    'fuel' => $order_ring_check->fuel,
                    'mile' => $order_ring_check->mile,
                    'note' => $order_ring_check->note,
                    'pic' => $path.$order_ring_check->pic
                );
            }
            $item_ids=array('left_front_tire_pressure','left_front_tread','left_front_brake_block',
                    'right_front_tire_pressure','right_front_tread','right_front_brake_block',
                    'left_after_tire_pressure','left_after_tread','left_after_brake_block',
                    'right_after_tire_pressure','right_after_tread','right_after_brake_block',
                    'left_front_age_limit','right_front_age_limit','left_after_age_limit','right_after_age_limit',
                    'left_front_facade','right_front_facade','left_after_facade','right_after_facade',
                    'left_front_flank_wear','right_front_flank_wear','left_after_flank_wear','right_after_flank_wear',
                    'speed_changing_box'
            );
            foreach($o3c as $_o3c){
                if(!in_array($_o3c->item_id,$item_ids)){
                    $_o3c->value=' ';
                }
            }
            foreach($error as $_r){
                if(!in_array($_r->item_id,$item_ids)){
                    $_r->value=' ';
                }
            }
            $check30=$light_check=$tire_pressure=$tread=$brake_block=$brake_disk=$valve_cock=$age_limit=$facade=$flank_wear=array();
            $light_check1=$tire_pressure1=$tread1=$brake_block1=$brake_disk1=$valve_cock1=$age_limit1=$facade1=$flank_wear1=new \stdClass;
            // foreach($o3c as $k=>$o){
            //     if($o->object_id=='light_check'){
            //         if($o->status==1){
            //             $light_check[]=$o;
            //         }else{
            //             $light_check1=$o;
            //         }
            //     }elseif($o->object_id=='four_wheel_check'){
            //         if($o->item_id=='left_front_tire_pressure' || $o->item_id=='right_front_tire_pressure' || $o->item_id=='left_after_tire_pressure' || $o->item_id=='right_after_tire_pressure'){
            //             if($o->status==1){
            //                 $tire_pressure[]=$o;
            //             }else{
            //                 $tire_pressure1=$o;
            //             }
            //         }
            //         if($o->item_id=='left_front_tread' || $o->item_id=='right_front_tread' || $o->item_id=='left_after_tread' || $o->item_id=='right_after_tread'){
            //             if($o->status==1){
            //                 $tread[]=$o;
            //             }else{
            //                 $tread1=$o;
            //             }
            //         }
            //         if($o->item_id=='left_front_brake_block' || $o->item_id=='right_front_brake_block' || $o->item_id=='left_after_brake_block' || $o->item_id=='right_after_brake_block'){
            //             if($o->status==1){
            //                 $brake_block[]=$o;
            //             }else{
            //                 $brake_block1=$o;
            //             }
            //         }
            //         if($o->item_id=='left_front_brake_disk' || $o->item_id=='right_front_brake_disk' || $o->item_id=='left_after_brake_disk' || $o->item_id=='right_after_brake_disk'){
            //             if($o->status==1){
            //                 $brake_disk[]=$o;
            //             }else{
            //                 $brake_disk1=$o;
            //             }
            //         }
            //         if($o->item_id=='left_front_valve_cock' || $o->item_id=='right_front_valve_cock' || $o->item_id=='left_after_valve_cock' || $o->item_id=='right_after_valve_cock'){
            //             if($o->status==1){
            //                 $valve_cock[]=$o;
            //             }else{
            //                 $valve_cock1=$o;
            //             }
            //         }
            //         if($o->item_id=='left_front_age_limit' || $o->item_id=='right_front_age_limit' || $o->item_id=='left_after_age_limit' || $o->item_id=='right_after_age_limit'){
            //             if($o->status==1){
            //                 $age_limit[]=$o;
            //             }else{
            //                 $age_limit1=$o;
            //             }
            //         }
            //         if($o->item_id=='left_front_facade' || $o->item_id=='right_front_facade' || $o->item_id=='left_after_facade' || $o->item_id=='right_after_facade'){
            //             if($o->status==1){
            //                 $facade[]=$o;
            //             }else{
            //                 $facade1=$o;
            //             }
            //         }
            //         if($o->item_id=='left_front_flank_wear' || $o->item_id=='right_front_flank_wear' || $o->item_id=='left_after_flank_wear' || $o->item_id=='right_after_flank_wear'){
            //             if($o->status==1){
            //                 $flank_wear[]=$o;
            //             }else{
            //                 $flank_wear1=$o;
            //             }
            //         }
            //     }else{
            //         $check30[]=$o;
            //     }
            // }
            // if(count($o3c)>0){
            //     $item_ids_temp=array(
            //         'left_front_age_limit','right_front_age_limit','left_after_age_limit','right_after_age_limit',
            //         'left_front_facade','right_front_facade','left_after_facade','right_after_facade',
            //         'left_front_flank_wear','right_front_flank_wear','left_after_flank_wear','right_after_flank_wear',
            //         'speed_changing_box'
            //     );
            //     $o3c_temp=Order30Check::where('order_id',Input::get('order_id'))->where('object_id','!=','general_suggest')->whereIn('item_id',$item_ids_temp)->select('id')->get();
            //     if(count($light_check) >= 1){
            //         $light_check[0]->item_name='灯光';
            //         $light_check[0]->item_id='light_check';
            //         $light_check[0]->status=1;
            //         $check30[]=$light_check[0];
            //     }else{
            //         $light_check1->item_name='灯光';
            //         $light_check1->item_id='light_check';
            //         $check30[]=$light_check1;
            //     }
            //     if(count($tire_pressure) >= 1){
            //         $tire_pressure[0]->item_name='胎压';
            //         $tire_pressure[0]->item_id='tire_pressure';
            //         $tire_pressure[0]->status=1;
            //         $check30[]=$tire_pressure[0];
            //     }else{
            //         $tire_pressure1->item_name='胎压';
            //         $tire_pressure1->item_id='tire_pressure';
            //         $check30[]=$tire_pressure1;
            //     }
            //     if(count($tread) >= 1){
            //         $tread[0]->item_name='胎纹';
            //         $tread[0]->item_id='tread';
            //         $tread[0]->status=1;
            //         $check30[]=$tread[0];
            //     }else{
            //         $tread1->item_name='胎纹';
            //         $tread1->item_id='tread';
            //         $check30[]=$tread1;
            //     }
            //     if(count($brake_block) >= 1){
            //         $brake_block[0]->item_name='制动片';
            //         $brake_block[0]->item_id='brake_block';
            //         $brake_block[0]->status=1;
            //         $check30[]=$brake_block[0];
            //     }else{
            //         $brake_block1->item_name='制动片';
            //         $brake_block1->item_id='brake_block';
            //         $check30[]=$brake_block1;
            //     }
            //     if(count($brake_disk) >= 1){
            //         $brake_disk[0]->item_name='制动盘';
            //         $brake_disk[0]->item_id='brake_disk';
            //         $brake_disk[0]->status=1;
            //         $check30[]=$brake_disk[0];
            //     }else{
            //         $brake_disk1->item_name='制动盘';
            //         $brake_disk1->item_id='brake_disk';
            //         $check30[]=$brake_disk1;
            //     }
            //     if(count($valve_cock) >= 1){
            //         $valve_cock[0]->item_name='气门嘴';
            //         $valve_cock[0]->item_id='valve_cock';
            //         $valve_cock[0]->status=1;
            //         $check30[]=$valve_cock[0];
            //     }
            //     /*else{
            //         $valve_cock1->item_name='气门嘴';
            //         $valve_cock1->item_id='valve_cock';
            //         $check30[]=$valve_cock1;
            //     }
            //     */
            //     if(sizeof($o3c_temp)){
            //         if(count($age_limit) >= 1){
            //             $age_limit[0]->item_name='年限';
            //             $age_limit[0]->item_id='age_limit';
            //             $age_limit[0]->status=1;
            //             $check30[]=$age_limit[0];
            //         }else{
            //             $age_limit1->item_name='年限';
            //             $age_limit1->item_id='age_limit';
            //             $check30[]=$age_limit1;
            //         }
            //         if(count($facade) >= 1){
            //             $facade[0]->item_name='外观';
            //             $facade[0]->item_id='facade';
            //             $facade[0]->status=1;
            //             $check30[]=$facade[0];
            //         }else{
            //             $facade1->item_name='外观';
            //             $facade1->item_id='facade';
            //             $check30[]=$facade1;
            //         }
            //         if(count($flank_wear) >= 1){
            //             $flank_wear[0]->item_name='偏磨';
            //             $flank_wear[0]->item_id='flank_wear';
            //             $flank_wear[0]->status=1;
            //             $check30[]=$flank_wear[0];
            //         }else{
            //             $flank_wear1->item_name='偏磨';
            //             $flank_wear1->item_id='flank_wear';
            //             $check30[]=$flank_wear1;
            //         }
            //     }
            // }
            $temp_arr=array('order_30_check'=>$o3c,'order_ring_check'=>$result,'exception'=>$error,'suggest'=>$suggest);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "checkRecords", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      lyt
     * @DateTime:    2017-02-15 14:04:54
     * @Description: 用于没有权限的额  暂时废弃
     */
    // public function checkRecordsNc(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //                 'order_id' => 'required',
    //             )
    //         );
        
    //         $order=Orders::find(Input::get('order_id'));
    //         if(is_null($order)){
    //             $response = Lang::get("scs_error.order_notexiet_40000");
    //             break;
    //         }
    //         $user=Users::where("id",$order->user_id)
    //             ->leftJoin('user_account','user_account.user_id','=','users.id')
    //             ->select('users.id','users.phone','users.register_source_id','users.real_name','users.sex','users.type','user_account.account_no','user_account.balance','user_account.credit')
    //             ->first();
    //         $uci=UserCarInfo::find($order->user_car_id);
    //         if(is_null($uci)&&$order->order_type==1){//服务单才判断
    //             $response = Lang::get("scs_error.order_car_info_notexit_40001");
    //             break;
    //         }
    //         $csi=DataCarStandardInfo::find($order->car_model_id);
    //         if(is_null($csi)&&$order->order_type==1){
    //             $response = Lang::get("scs_error.order_car_model_notexit_40002");
    //             break;
    //         }
    //         // $number=Orders::where("car_no",$msc->car_no)->whereIn("status",array(1216,1017,1117,1317,1018))->max("mileage");
    //         $car_arr=array(
    //             "car_no"=>$order->car_no,
    //             "kilometre"=>$order->mileage,
    //             "befor_kilometre"=>isset($uci)?$uci->mileage:0,
    //             "vin"=>isset($uci)?$uci->vin_code:"",
    //             "note"=>isset($uci)?$uci->note:"",
    //             "desc"=>isset($uci)?$uci->note:"",
    //             "brand_name"=>isset($csi)?$csi->brand_name:"",
    //             "series_name"=>isset($csi)?$csi->series_name:"",
    //             "model_name"=>isset($csi)?$csi->model_name:"",
    //             "model_id"=>isset($csi)?$csi->id:0,
    //             "user_car_id"=>$order->user_car_id,
    //             "insurance"=>isset($uci)?$uci->insurance:'',
    //         );
    //         $engineer_info=array();
    //         if($order->engineer_id != 0){
    //             $engineer_info=MaintenanceEngineers::where('id',$order->engineer_id)->where('type','shop')->select('id','name')->first();
    //         }
    //         $order->type=$user->type;
    //         if($user->type==2){//如果是企业用户
    //             $compnay=Companys::find($user->id);
    //             $order->company_name=isset($compnay)?$compnay->name:"";
    //             $ucd=UserCarDesc::find($uci->id);
    //             $order->card_no=isset($ucd) ? $ucd->card_no : "";
    //         }
    //         if($order->tittle=="先生"){
    //             $sex=1;
    //         }elseif($order->tittle=="女士"){
    //             $sex=2;
    //         }else{
    //             $sex=0;
    //         }
    //         $order->sex=$sex;

    //         //关联订单信息
    //         $or=OrderRelations::where('mirror_order_id',Input::get('order_id'))->first();
    //         $order->relation_order_id=isset($or->order_id) ? $or->order_id : '';

            
    //         $ms=MaintenanceShops::find($order->shop_id);
    //         if(is_null($ms)){
    //             $response = Lang::get("scs_error.scs_user_shop_error_21013");
    //             break;
    //         }            
    //         $print_name=empty($ms->print_title) ? "北京安惠汽车服务有限公司".$ms->name : $ms->print_title;
    //         $shop_info=array(
    //                 'shop_name'=>$ms->name,
    //                 'shop_address' =>$ms->address,
    //                 'shop_desc'=>$ms->desc,
    //                 'business_is_enabled'=>$ms->business_is_enabled,
    //                 'print_name'=>$print_name);
           
    //         $temp_arr=array("order_info"=>$order,"user_car_info"=>$car_arr,"engineer_info"=>$engineer_info,"user_info"=>$user,"shop_info"=>$shop_info);


    //         $o3c=Order30Check::where('order_id',Input::get('order_id'))->where('object_id','!=','general_suggest')->get();
    //         $suggest=Order30Check::where('order_id',Input::get('order_id'))->where('object_id','general_suggest')->first();
    //         $error=Order30Check::where('order_id',Input::get('order_id'))->where('status',1)->where('object_id','!=','general_suggest')->get();
    //         $order_ring_check=OrderRingCheck::find(Input::get('order_id'));
    //         if(is_null($order_ring_check)){
    //             $result = array(
    //                 'order_id' => Input::get('order_id'),
    //                 'sound' => 0,
    //                 'cigarette_lighter' => 0,
    //                 'front_mark' => 0,
    //                 'tire_cover' => 0,
    //                 'rear_mark' => 0,
    //                 'axle_cover' => 0,
    //                 'antenna' => 0,
    //                 'fire_extinguisher' => 0,
    //                 'fuel' => 0,
    //                 'mile' => 0,
    //                 'note' => '',
    //                 'pic' => ''
    //             );
    //         }else{
    //             $path=Config::get('config.ring_check_img_url');
    //             $result = array(
    //                 'order_id' => Input::get('order_id'),
    //                 'sound' => $order_ring_check->sound,
    //                 'cigarette_lighter' => $order_ring_check->cigarette_lighter,
    //                 'front_mark' => $order_ring_check->front_mark,
    //                 'tire_cover' => $order_ring_check->tire_cover,
    //                 'rear_mark' => $order_ring_check->rear_mark,
    //                 'axle_cover' => $order_ring_check->axle_cover,
    //                 'antenna' => $order_ring_check->antenna,
    //                 'fire_extinguisher' => $order_ring_check->fire_extinguisher,
    //                 'fuel' => $order_ring_check->fuel,
    //                 'mile' => $order_ring_check->mile,
    //                 'note' => $order_ring_check->note,
    //                 'pic' => $path.$order_ring_check->pic
    //             );
    //         }
    //         $item_ids=array('left_front_tire_pressure','left_front_tread','left_front_brake_block',
    //                 'right_front_tire_pressure','right_front_tread','right_front_brake_block',
    //                 'left_after_tire_pressure','left_after_tread','left_after_brake_block',
    //                 'right_after_tire_pressure','right_after_tread','right_after_brake_block',
    //                 'left_front_age_limit','right_front_age_limit','left_after_age_limit','right_after_age_limit',
    //                 'left_front_facade','right_front_facade','left_after_facade','right_after_facade',
    //                 'left_front_flank_wear','right_front_flank_wear','left_after_flank_wear','right_after_flank_wear',
    //                 'speed_changing_box'
    //         );
    //         foreach($o3c as $_o3c){
    //             if(!in_array($_o3c->item_id,$item_ids)){
    //                 $_o3c->value=' ';
    //             }
    //         }
    //         foreach($error as $_r){
    //             if(!in_array($_r->item_id,$item_ids)){
    //                 $_r->value=' ';
    //             }
    //         }           
    //         $temp_arr=array('order_info'=>$temp_arr,'order_30_check'=>$o3c,'order_ring_check'=>$result,'exception'=>$error,'suggest'=>$suggest);
    //         $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
    //         }while(false);
    //     Log::info("info", array("system" => "scs" ,"event" => "checkRecords", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }

   /**
    * @Author:      lyt
    * @DateTime:    2017-02-23 16:53:59
    * @Description: 新版本的检测记录
    */
    public function checkRecorDetection(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            $order_ring_check=OrderRingCheck::find(Input::get('order_id'));
            if(is_null($order_ring_check)){
                $result = array(
                    'order_id' => Input::get('order_id'),
                    'sound' => 0,
                    'cigarette_lighter' => 0,
                    'front_mark' => 0,
                    'tire_cover' => 0,
                    'rear_mark' => 0,
                    'axle_cover' => 0,
                    'antenna' => 0,
                    'fire_extinguisher' => 0,
                    'fuel' => 0,
                    'mile' => 0,
                    'note' => '',
                    'pic' => ''
                );
            }else{
                $path=Config::get('config.ring_check_img_url');
                $result = array(
                    'order_id' => Input::get('order_id'),
                    'sound' => $order_ring_check->sound,
                    'cigarette_lighter' => $order_ring_check->cigarette_lighter,
                    'front_mark' => $order_ring_check->front_mark,
                    'tire_cover' => $order_ring_check->tire_cover,
                    'rear_mark' => $order_ring_check->rear_mark,
                    'axle_cover' => $order_ring_check->axle_cover,
                    'antenna' => $order_ring_check->antenna,
                    'fire_extinguisher' => $order_ring_check->fire_extinguisher,
                    'fuel' => $order_ring_check->fuel,
                    'mile' => $order_ring_check->mile,
                    'note' => $order_ring_check->note,
                    'pic' => $path.$order_ring_check->pic
                );
            }
            $de=OrderDetection::getOrderDetection(Input::get('order_id'));            
            $de["order_ring_check"]=$result;
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $de);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "checkRecords", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      lyt
     * @DateTime:  2017-03-14 09:55:19
     * @Description: 没有权限验证的检测报告接口
     */
    public function checkRecorDetectionNc(){
        $validator = Validator::make(Input::all(),
            array(
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            $user=Users::where("id",$order->user_id)
                ->leftJoin('user_account','user_account.user_id','=','users.id')
                ->select('users.id','users.phone','users.register_source_id','users.real_name','users.sex','users.type','user_account.account_no','user_account.balance','user_account.credit')
                ->first();
            $uci=UserCarInfo::find($order->user_car_id);
            if(is_null($uci)&&$order->order_type==1){//服务单才判断
                $response = Lang::get("scs_error.order_car_info_notexit_40001");
                break;
            }
            $csi=DataCarStandardInfo::find($order->car_model_id);
            if(is_null($csi)&&$order->order_type==1){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            // $number=Orders::where("car_no",$msc->car_no)->whereIn("status",array(1216,1017,1117,1317,1018))->max("mileage");
            $car_arr=array(
                "car_no"=>$order->car_no,
                "kilometre"=>$order->mileage,
                "befor_kilometre"=>isset($uci)?$uci->mileage:0,
                "vin"=>isset($uci)?$uci->vin_code:"",
                "note"=>isset($uci)?$uci->note:"",
                "desc"=>isset($uci)?$uci->note:"",
                "brand_name"=>isset($csi)?$csi->brand_name:"",
                "series_name"=>isset($csi)?$csi->series_name:"",
                "model_name"=>isset($csi)?$csi->model_name:"",
                "model_id"=>isset($csi)?$csi->id:0,
                "user_car_id"=>$order->user_car_id,
                "insurance"=>isset($uci)?$uci->insurance:'',
            );
            $engineer_info=array();
            if($order->engineer_id != 0){
                $engineer_info=MaintenanceEngineers::where('id',$order->engineer_id)->where('type','shop')->select('id','name')->first();
            }
            $order->type=$user->type;
            if($user->type==2){//如果是企业用户
                $compnay=Companys::find($user->id);
                $order->company_name=isset($compnay)?$compnay->name:"";
                $ucd=UserCarDesc::find($uci->id);
                $order->card_no=isset($ucd) ? $ucd->card_no : "";
            }
            if($order->tittle=="先生"){
                $sex=1;
            }elseif($order->tittle=="女士"){
                $sex=2;
            }else{
                $sex=0;
            }
            $order->sex=$sex;

            //关联订单信息
            $or=OrderRelations::where('mirror_order_id',Input::get('order_id'))->first();
            $order->relation_order_id=isset($or->order_id) ? $or->order_id : '';

            
            $ms=MaintenanceShops::find($order->shop_id);
            if(is_null($ms)){
                $response = Lang::get("scs_error.scs_user_shop_error_21013");
                break;
            }            
            $print_name=empty($ms->print_title) ? "北京安惠汽车服务有限公司".$ms->name : $ms->print_title;
            $shop_info=array(
                    'shop_name'=>$ms->name,
                    'shop_address' =>$ms->address,
                    'shop_desc'=>$ms->desc,
                    'business_is_enabled'=>$ms->business_is_enabled,
                    'print_name'=>$print_name);
           
            $temp_arr=array("order_info"=>$order,"user_car_info"=>$car_arr,"engineer_info"=>$engineer_info,"user_info"=>$user,"shop_info"=>$shop_info);


            $order_ring_check=OrderRingCheck::find(Input::get('order_id'));
            if(is_null($order_ring_check)){
                $result = array(
                    'order_id' => Input::get('order_id'),
                    'sound' => 0,
                    'cigarette_lighter' => 0,
                    'front_mark' => 0,
                    'tire_cover' => 0,
                    'rear_mark' => 0,
                    'axle_cover' => 0,
                    'antenna' => 0,
                    'fire_extinguisher' => 0,
                    'fuel' => 0,
                    'mile' => 0,
                    'note' => '',
                    'pic' => ''
                );
            }else{
                $path=Config::get('config.ring_check_img_url');
                $result = array(
                    'order_id' => Input::get('order_id'),
                    'sound' => $order_ring_check->sound,
                    'cigarette_lighter' => $order_ring_check->cigarette_lighter,
                    'front_mark' => $order_ring_check->front_mark,
                    'tire_cover' => $order_ring_check->tire_cover,
                    'rear_mark' => $order_ring_check->rear_mark,
                    'axle_cover' => $order_ring_check->axle_cover,
                    'antenna' => $order_ring_check->antenna,
                    'fire_extinguisher' => $order_ring_check->fire_extinguisher,
                    'fuel' => $order_ring_check->fuel,
                    'mile' => $order_ring_check->mile,
                    'note' => $order_ring_check->note,
                    'pic' => $path.$order_ring_check->pic
                );
            }
            $de=OrderDetection::getOrderDetection(Input::get('order_id'));            
            $de["order_ring_check"]=$result;
            $de['order_info']=$temp_arr;
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $de);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "checkRecorDetectionNc", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2017-02-23 17:08:39
     * @Description: 更新 异常项目的报价
     */
    public function saveDetectionAmount(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'id' => 'required',
                'amount' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            $de=OrderDetection::where("id",Input::get("id"))->where("order_id",Input::get("order_id"))->where("level",2)->first();
            if(is_null($de)){
                $response = Lang::get("scs_error.order_check_error_40077");
                break;
            } 
            $de->amount=Input::get("amount");
            $de->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array(
                'order_id' => Input::get("order_id")
            ));
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "saveDetectionAmount", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-3-14 10:23:13
     * @Description: 维修记录
     */
    public function maintenanceRecord(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no' => 'required',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_ids=Orders::where("car_no",Input::get('car_no'))->whereIn("status",Orders::$complete)->select('order_id')->where("pay_time",'>',"2016-01-01 00:00:00")->orderBy("pay_time","DESC")->take(10)->get()->toArray();
            $orderProduct=OrderProduct::getOrderProductByOrderIds($order_ids);
            $allHour=OrderProduct::getOrderHoursByOrderIds($order_ids);
            $orderProduct['allHour']=$allHour;
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $orderProduct);
        }while(false);
        // Log::info("info", array("system" => "scs" ,"event" => "maintenanceRecords", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-4-26 14:37:32
     * @Description: 优惠券信息
     */
    public function coupons(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $coupon_info=CouponOrderInfo::where("order_id",Input::get('order_id'))
                ->where("coupon_order_info.val_status",1)
                ->leftJoin('coupon_base_info','coupon_order_info.coupon_base_info_id','=','coupon_base_info.id')
                ->leftJoin('coupons','coupons.id','=','coupon_order_info.coupon_id')
                ->select('coupons.id','coupons.status','coupon_base_info.name','coupon_base_info.amount','coupon_base_info.type','coupon_base_info.pack_id','coupon_order_info.status as check_status')
                ->get();
            $total=0;
            foreach($coupon_info as $_coupon){
                if($_coupon->type==2||$_coupon->type==5){
                    $op=OrderProduct::where('order_id',Input::get('order_id'))->where('status',1)->where("coupon_discount",">","0")->sum("coupon_discount");
                    if($_coupon->check_status==1){
                        $_coupon->amount=$op;
                    }else{
                        $_coupon->amount=0;
                    }
                    $total+=$_coupon->amount;
                }else{
                    $total+=$_coupon->amount; 
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('coupon_info'=>$coupon_info,'total'=>$total));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "coupons", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response); 
    }

    /**
     * @Author:      lyt
     * @DateTime:    2017-03-10 14:58:02
     * @Description: 验证优惠券券码
     */
    public function verification_coupons(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'code' => 'required',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $order=Orders::find(Input::get('order_id'));
            if(is_null($order) || $order->order_tyoe==2){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            $op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }
            if(!in_array($order->status, Orders::$change_price)){//订单状态是否为服务开始或结束
                $response = Lang::get("scs_error.order_status_error_40024");
                break;
            }
            $response=Coupons::verification_coupons($order,Input::get("code"));
            // $response = array('code' => 0, 'msg' => 'ok', 'result' => array('coupon_info'=>$coupon_info,'total'=>$total));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "coupons", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response); 
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-16 14:19:37
     * @Description: 发短信
     */
    public function send(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "phone"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
    
            $phone=Input::get('phone');
            $area='010';
            $time_out_default = Config::get("user.time_out_default");
    
            //检查手机号是否下发验证码
            $record = UserCheckCode::getCheckCode($phone,$area);
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                            'check_code' => $record->check_code // todo 调试使用
                        ));
                    break;
                }else{ //超过限时
                    UserCheckCode::delCheckCode($phone,$area);
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您修改用户信息的验证码为：'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "send", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
    
            //记录数据库
            $data = array(
                'phone' => $phone,
                'area' => $area,
                'check_code' => $check_code,
                'created_at' => Common::num2DateTime(time()),
                'out_time_at' => Common::num2DateTime(time() + $time_out_default),
                'send_id' => $sms_send_record_id,
            );
    
            try {
                UserCheckCode::insCheckCode($data);
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "sms_check_code", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_create_error_1002");
                break;
            }
    
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                    'check_code' => $check_code // todo 调试使用
                ));
    
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-16 13:55:12
     * @Description: 修改用户信息
     */
    public function updateUser(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "code" => 'numeric',
                'user_id' => 'required',
                'name' => 'required',
                'phone' => 'required',
                'sex' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>'');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $users=Users::where('phone',Input::get('phone'))->first();
            $user=Users::where('id',Input::get('user_id'))->where('status',1)->first();
            if($users){
                if($users->id!=$user->id){
                    $response = Lang::get("scs_error.user_error_21010");
                    break;
                }
            }
            if(!$user){
                $response = Lang::get("scs_error.user_error_21009");
                break;
            }
    
            $phone=$user->phone;
            $area="010";
            //判断验证码是否存在
            $record = UserCheckCode::getCheckCode($phone,$area);
            if(is_null($record)){ //没有记录
                $response = Lang::get("error.user_login_checkcode_null_1012");
                break;
            }
            //校验是否超过时限
            if( time() > Common::datetime2Num($record->out_time_at) ){
                $response = Lang::get("error.user_login_checkcode_timeout_1013");
                break;
            }

            //校验验证码是否匹配
            if($record->check_code != Input::get('code')){
                $response = Lang::get("error.user_login_checkcode_error_1014");
                break;
            }
           
            $user->real_name=Input::get('name');
            $user->phone=Input::get('phone');
            $user->sex=Input::get('sex');
            $user->save();
            if($user->type==2){
                Companys::where("id",$user->id)->update(array("name"=>Input::get('name'),"phone"=>Input::get('phone')));
            }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-24 10:43:24
     * @Description: 折扣申请
     */
    public function apply_discount(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "type" => 'required|numeric',
                'approve_type' => 'required',
                'discount' => 'required',
                'relation' => 'required',
                'reason' => 'required',
                'order_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>'');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){//服务单才判断
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->order_type==2 && $order->car_no==""){
                if(Input::get('type')==2){
                    $response = Lang::get("scs_error.order_discount_error_42006");
                    break;
                }
            }
            if(Input::get('type')==1){
                $id=Input::get('id');
                $ca=CityAuthorization::find($id);
                $phone=$ca->phone;
                $approve_name=$ca->name;
                $response=$this->checkCode($phone,Input::get('order_id'),Input::get('code'));
                if($response['code']!=0){
                    break;
                }
            }else if(Input::get('type')==2 && Input::get('approve_type')==1){
                $id=Input::get('id');
                $sc=SCUser::find($id);
                $phone=$sc->phone;
                $approve_name=$sc->real_name;
                $response=$this->checkCode($phone,Input::get('order_id'),Input::get('code'));
                if($response['code']!=0){
                    break;
                }
            }else if(Input::get('type')==2 && Input::get('approve_type')==2){
                $sc=SCUser::where('user_name',Input::get('username'))->where('password',strtoupper(md5(Input::get('password'))))->where('status',1)->first();
                if(is_null($sc)){
                    $response = Lang::get("scs_error.scs_user_not_exiet21009");
                    break;
                }
                if($sc->title!=1){
                    $response = Lang::get("scs_error.login_user_error_21016");
                    break;
                }
                $approve_name=$sc->real_name;
            }
            if(Input::get('type')==1){
                $cdt=CarDiscountTemp::where('order_id',Input::get('order_id'))->where('status',1)->first();
                if($cdt){
                    $cdt->type=Input::get('type');
                    $cdt->dis=Input::get('discount');
                    $cdt->reason=Input::get('reason');
                    $cdt->relation=Input::get('relation');
                    $cdt->created_by=$sc_user->id;
                    $cdt->approve_name=$approve_name;
                    $cdt->save();
                }else{
                    $car_discount_temp=new CarDiscountTemp;
                    $car_discount_temp->order_id=Input::get('order_id');
                    $car_discount_temp->type=Input::get('type');
                    $car_discount_temp->dis=Input::get('discount');
                    $car_discount_temp->reason=Input::get('reason');
                    $car_discount_temp->status=1;
                    $car_discount_temp->relation=Input::get('relation');
                    $car_discount_temp->created_by=$sc_user->id;
                    $car_discount_temp->approve_name=$approve_name;
                    $car_discount_temp->save();
                }
            }else{
                $discount=Input::get('discount');
                if(!in_array($discount,array(0.8,0.85,0.90,0.95))){
                    $response = Lang::get("scs_error.order_discount_error_42005");
                    break;
                }
                $cdp=CarDiscountPermanent::where('car_no',$order->car_no)->where('status',1)->first();
                if($cdp){
                    $cdp->dis=Input::get('discount');
                    $cdp->reason=Input::get('reason');
                    $cdp->status=1;
                    $cdp->relation=Input::get('relation');
                    $cdp->created_by=$sc_user->id;
                    $cdp->approve_name=$approve_name;
                    $cdp->start_time=date("Y-m-d H:i:s",time());
                    $cdp->end_time=date("Y-m-d H:i:s",strtotime('+1 year'));
                    $cdp->save();
                }else{
                    $cdp=new CarDiscountPermanent;
                    $cdp->car_no=$order->car_no;
                    $cdp->dis=Input::get('discount');
                    $cdp->reason=Input::get('reason');
                    $cdp->status=1;
                    $cdp->relation=Input::get('relation');
                    $cdp->created_by=$sc_user->id;
                    $cdp->approve_name=$approve_name;
                    $cdp->start_time=date("Y-m-d H:i:s",time());
                    $cdp->end_time=date("Y-m-d H:i:s",strtotime('+1 year'));
                    $cdp->save();
                }
            }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "apply_discount", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-24 12:01:13
     * @Description: 验证码验证
     */
    public function checkCode($phone,$order_id,$code){
        //判断验证码是否存在
        $record = UserCheckCodeUpgrade::where('business_id',$order_id)->where("business_type","discount_apply")->where("phone",$phone)->first();
        if(is_null($record)){ //没有记录
            return $response = Lang::get("error.user_login_checkcode_null_1012");
        }
        //校验是否超过时限
        if( time() > Common::datetime2Num($record->out_time_at) ){
            return $response = Lang::get("error.user_login_checkcode_timeout_1013");
        }
        
        //校验验证码是否匹配
        if($record->check_code != $code){
            return $response = Lang::get("error.user_login_checkcode_error_1014");
        }
        $response = array('code' => 0, 'msg' => 'ok','result'=>'');
        return $response;
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-24 14:18:55
     * @Description: 发短信
     */
    public function sendMsg(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "id"=>'required',
                'type' => 'required',
                'order_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
    
            $phone="";
            $area='';
            $order_id=Input::get('order_id');
            $return_order_id=Input::get('return_order_id');
            $id=Input::get('id');
            if(Input::get('type')==1){
                $ca=CityAuthorization::find($id);
                $phone=$ca->phone;
            }else{
                $sc=SCUser::find($id);
                $phone=$sc->phone;
            }
            $time_out_default = Config::get("user.time_out_default");
    
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where('business_id',Input::get("order_id"))->where("business_type","discount_apply")->where("phone",$phone)->first();
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请折扣业务，订单号：'.$order_id.'，您的授权码为'.$record->check_code.'，请确认是否批准。');
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMsg", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                    ));
                    break;
                }else{ //超过限时
                    $record->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请折扣业务，订单号：'.$order_id.'，您的授权码为'.$check_code.'，请确认是否批准。');
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMsg", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
    
            $record = new UserCheckCodeUpgrade;
            $record->business_type="discount_apply";
            $record->business_id=Input::get("order_id");
            $record->phone=$phone;
            $record->area="";
            $record->check_code=$check_code;
            $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
            $record->send_id=$sms_send_record_id;           
            $record->save();
    
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                ));
    
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-21 11:33:37
     * @Description: 折扣历史
     */
    public function discountHistory(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'car_no' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_ids=Orders::where('car_no', strtoupper(Input::get('car_no')))->whereIn('status',Orders::$complete)->select('order_id')->get()->toArray();
            $order_ids=array_column($order_ids,'order_id');
            $cdt=CarDiscountTemp::where('status',1)->whereIn('order_id',$order_ids)->where('type',1)->orderBy('created_at')->get();
            $cdp=CarDiscountPermanent::where('car_no',strtoupper(Input::get('car_no')))->where('status',1)->first();
            $discount=array();
            foreach($cdt as $_cdt){
                $_cdt->type=1;
                $discount[]=$_cdt;
            }
            if(isset($cdp)){
                $cdp->type=2;
                $discount[]=$cdp;
            }else{
                $cdp=array();
            }
            
            $response['result']=array('cdt'=>$discount);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-31 10:21:49
     * @Description: 测试订单计算方法
     */
    public function test(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            Orders::calculate(Input::get('order_id'));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-12-8 16:38:07
     * @Description: 用户标签列表
     */
    public function labelList(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $ls=Labels::All();
            $response['result']=array('labels'=>$ls);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "labelList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-12-8 16:38:07
     * @Description: 用户标签列表
     */
    public function save_user_label(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'user_id' => 'required',
                'label_ids' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array());
        $label_ids=json_decode(Input::get('label_ids'),1);
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            UserLabel::where('user_id',Input::get('user_id'))->delete();
            foreach($label_ids as $li){
                $ul=new UserLabel;
                $ul->user_id=Input::get('user_id');
                $ul->label_id=$li;
                $ul->save();
            }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-12-8 16:38:07
     * @Description: 用户标签列表
     */
    public function user_label(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'user_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $ul=UserLabel::leftJoin('labels','labels.id','=','user_label.label_id')
                ->where('user_id',Input::get('user_id'))
                ->select('user_label.*','labels.name')
                ->get();
            $response['result']=array('user_label'=>$ul);
        }while(false);
        // Log::info("info", array("system" => "scs" ,"event" => "labelList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /*
     * @Author:      zhaoyang
     * @DateTime:    2017-07-03
     * 扫描驾驶本列表
     * http://api.anhui.com/v1/scs/order/drivingLicenseNewList?token=ca3ab3f67239bc498012f5f60ef1da11
     * */
    public function drivingLicenseNewList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            
            $sql = " (select id from `driving_license` where `shop_id` = ? and (car_no regexp '[\\\*]' or car_no regexp '[\\\-]'))";
            $sql = "select * from driving_license where `shop_id` = ? and id not in($sql)  order by updated_at desc limit 5";
            $list = DB::select($sql, array($sc_user->shop_id,$sc_user->shop_id));
            $response = array('code' => 0, 'msg' => 'ok', 'result' =>array("list"=>$list));
        } while (false);
        // Log::info("info", array("system" => "scs" ,"model" => "order", "event" => "drivingLicenseNewList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-10-17 16:04:11
     * @Description: 查找最近门店的扫描纪录不过滤
     */
    public function drivingLicenseShopList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "size"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }            
            $sql = "select * from driving_license where `shop_id` = ?  order by updated_at desc limit ?";
            $list = DB::select($sql,array($sc_user->shop_id,Input::get("size",3)));
            $response = array('code' => 0, 'msg' => 'ok', 'result' =>array("list"=>$list));
        } while (false);
        // Log::info("info", array("system" => "scs" ,"model" => "order", "event" => "drivingLicenseShopList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
        /*
     * @Author:      zhaoyang
     * @DateTime:    2017-07-03
     * 扫描驾驶本列表
     * http://api.anhui.com/v1/scs/order/drivingLicenseNewList?token=ca3ab3f67239bc498012f5f60ef1da11
     * */
    public function carNoImg(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $info = DrivingLicenseNew::select('img')->where('car_no',Input::get('car_no'))->orderby('created_at','desc')->first();
            $img = is_null($info) ? null : $info->img;

            $response = array('code' => 0, 'msg' => 'ok', 'result' =>array("img"=>$img));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "order", "event" => "drivingLicenseNewList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /*
     * @Author:      zhaoyang
     * @DateTime:    2017-07-03
     * 获取最新的驾驶本的信息
     * http://api.anhui.com/v1/scs/order/LicenseNewInfo?token=ca3ab3f67239bc498012f5f60ef1da11
     * */
    public function licenseNewInfo(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok','result' => ["info"=>""]);
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $car_no = Input::get("car_no");
            if(!$car_no) {
                $response = Lang::get("scs_error.login_token_error_10000");
                break;
            }
            $License = DrivingLicense::orderby("updated_at","desc")->where("car_no",$car_no)->first();
            $updated_at = !empty($License['updated_at']) ? strtotime($License['updated_at']) :0;
            $License_new = DrivingLicenseNew::orderby("updated_at","desc")->where("car_no",$car_no)->first();
            $updated_at_new = !empty($License_new['updated_at']) ? strtotime($License_new['updated_at']) :0;
            if ($updated_at != 0 &&$updated_at_new != 0) { 
                $License->is_lock = 0;
                $License->source = 1;    //驾驶证信息来源  1扫描的行驶本  2使用过的行驶本
                $License_new->source = 2;
                $info = $updated_at > $updated_at_new ? $License : $License_new;   //如果都存在，取时间最新的
            }else if ($updated_at != 0) { //如果只有一个存在，扫描行驶本存在的时候
                $License->is_lock = 0;
                $License->source = 1;
                $info = $License;
            }else if ($updated_at_new != 0){//如果只有一个存在，使用过的行驶本存在的时候
                $License_new->source = 2;
                $info = $License_new;
            }else if($updated_at == 0 && $updated_at_new == 0){  //都不存在的情况
                break;
            }
            if ($info->source == 1){
                $License_new_agin = DrivingLicenseNew::where(["car_no"=>$info["car_no"],"vin"=>$info["vin"],"send_time"=>$info["send_time"]])
                        ->orderby("updated_at","desc")->where("car_no",$car_no)->first();
                if (!empty($License_new_agin['is_lock'])) {    //判断是否锁定,如果是锁定还是用 "使用过的行驶本"
                    $info = $License_new;
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["info"=>$info]);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "order", "event" => "licenseNewInfo", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * @Author:      zhaoyang
     * @DateTime:    2017-07-04
     * 获取最新的门店扫描驾驶本信息
     * http://api.anhui.com/v1/scs/order/licenseInShop?token=ca3ab3f67239bc498012f5f60ef1da11&shop_id=1
     * */
    public function licenseInShop(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["info"=>""]);
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $car_no = Input::get("car_no");
            if(!$car_no) {
                $response = Lang::get("scs_error.login_token_error_10000");
                break;
            }
            $License = DrivingLicense::orderby("updated_at","desc")->where("car_no",$car_no)->where("shop_id",$sc_user->shop_id)->first();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["info"=>$License]);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "order", "event" => "licenseInShop", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-8-29 下午2:57
     * @Description:     撤回订单、终止订单时 发送短信验证码
     * @param string $token     用户token
     * @param int $id           店长id
     * @param string $order_id  订单id
     * @param int $type  验证码类型业务类型 (1:终止订单;2:撤回订单;)
     * @link http://api.anhui.com/v1/scs/order/sendTextMessage?token=38b8ea29bc973529477253c773f9b745&id=155&order_id=15294751417259&type=1
     */
    public function sendTextMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'order_id' => 'required',
                'type' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get('scs_error.args_error_10000');
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $id             = Input::get('id');         //店长id
            $order_id       = Input::get('order_id');   //订单id
            $type           = Input::get('type');       //验证码类型业务类型  1:终止订单;2:撤回订单;
            //获取店长相关信息
            $user_info = SCUser::find($id);
            if(!$user_info){
                $response = Lang::get('scs_error.user_error_21009');
                break;
            }
            switch ($type) {
                case 1:     //终止订单
                    $business_type = 'stop_order';      //验证码类型业务类型
                    $content = '【安惠养车】您好，'.$sc_user->shop->name.'，申请订单终止业务，订单号：'.$order_id.'，您的授权码为';
                    break;
                case 2:     //撤回订单
                    $business_type = 'withdraw_order';  //验证码类型业务类型
                    $content = '【安惠养车】您好，'.$sc_user->shop->name.'，申请订单撤回业务，订单号：'.$order_id.'，您的授权码为';
                    break;

                default:
                    $response = Lang::get('scs_error.args_error_10000');
                    break;
            }
            $area               = '';     //区号
            $phone              = $user_info->phone;
            $time_out_default   = Config::get("user.time_out_default");   //有效时间
            
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where('business_id', $order_id)
                    ->where('business_type', $business_type)
                    ->where('phone', $phone)
                    ->first();
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area, $phone, $content.''.$record->check_code);
                    } catch (Exception $e) {
                        Log::error('error', array('system' => 'scs' ,'event' => 'sendTextMessage', 'input' =>Input::all(), 'exception' => $e));
                        $response = Lang::get('error.user_sms_check_code_send_error_1003');
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                        ));
                    break;
                }else{ //超过限时
                    $record->delete();
                }
            }
            //超过时限和没有记录    生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area, $phone, $content.''.$check_code);
            } catch (Exception $e) {
                Log::error("error", array('system' => 'scs', 'event' => 'sendTextMessage', 'input' =>Input::all(), 'exception' => $e));
                $response = Lang::get('error.user_sms_check_code_send_error_1003');
                break;
            }
            
            $record = new UserCheckCodeUpgrade;
            $record->business_type = $business_type;
            $record->business_id = $order_id;
            $record->phone = $phone;
            $record->area = $area;
            $record->check_code = $check_code;
            $record->out_time_at = Common::num2DateTime(time() + $time_out_default);
            $record->send_id = $sms_send_record_id;           
            $record->save();
            
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                ));
            
        }while(false);
        Log::info("info", array('system' => 'scs', 'event' => 'sendTextMessage', 'input' =>Input::all(), 'output' => $response));
        return json_encode($response);
    }
}